texts: Categorizing Projectiles in an arcade shooter (multiple inheritance?)

texts:
I have been working on a simple arcade shooter in Java in the vein of missile command/space invaders.  I've made a base Projectile class and have been extending other Projectile types from it. This has been a nice way so far for me to keep the same basic behavior of the projectile, while experimenting with new ideas, like a missile projectile, electric projectile, bursting, etc.  Before I went further though, I started to realize I needed to think about this in a better organized way because of this problem: what if I wanted to make a projectile that has features of more than one type?

Like, for example, if I wanted to make a projectile that is both seeking as well as bursting, or seeking, and shocking, etc... or a projectile that is all of the types.  It seems repetitive then for me to have to create a class for each combination type. If I tried to do this on my own now, I'd essentially be copying n' pasting code from one type into another to make the hybrid type.

What's the best way to organize this type of design?  It seems as though I need multiple inheritance. I don't understand how that works exactly in runtime though and how to ensure that the functions that I'm required to implement will be called and perform the behaviors I want, given any projectile.

Maybe in code it looks something like this?

Projectile p = new Projectile(loc, vel);
p.attachBehavior('electric');
p.attachBehavior('bursting');

and Projectile already inherits all the types possible? (It seems like it will make the Projectile class really huge though) and so perhaps attachBehavior() is essentially a loop that cycles through all the interfaces that the Projectile has?

However, looking at this post on Java and multiple inheritance (https://stackoverflow.com/questions/21824402/java-multiple-inheritance?lq=1), it seems as though even the base Projectile would also be an inherited thing. So I'm a bit confused about how to design such behaviors. (Even more confused when I think that some projectiles like lazers/beams behave instantaneously compared to gun bullets)

Also, when I'm doing things like this, I'm a bit wary about how to code in such a way that I'm not running more for loops than I should. Like for example, the missile projectile type needs to loop through the enemies to find the closest enemy, but the electric type, which shoots out an arc to a badguy will also need to loop through the enemies to see if its close to it.  Instead of having one for loop, by having these two behaviors, haven't I now made the game run potentially slower because I'm going through two for loops now as opposed to just making a distinct hybrid projectile class that checks for both conditions in the same for loop?


texts:
I have ui.Image1 with Mask component and ui.Image2 that is placed inside ui.Image1, then I want to save the result to Texture2d to save the resulting image to png.

Sprite sprite = sourceImage.sprite;
Texture2D newText = new Texture2D((int)sprite.rect.width,(int)sprite.rect.height);
Color[] newColors = sprite.texture.GetPixels((int)sprite.textureRect.x,
                                             (int)sprite.textureRect.y,
                                             (int)sprite.textureRect.width,
                                             (int)sprite.textureRect.height );
newText.SetPixels(newColors);
newText.Apply();

System.IO.File.WriteAllBytes(_SavePath + "photo.png", newText.EncodeToPNG());

but I have the error:

  Texture 'mask' is not readable, the texture memory can not be accessed
  from scripts. You can make the texture readable in the Texture Import
  Settings.

If I change the texture type of 'mask' from Sprite to Advanced - the mask stop work. Let me know what need to do.


texts: Converted XWM(A) files get silence at the end

texts:
I am writing a playback mechanism for looping background music with XAudio2 and SharpDX.

I converted some perfectly looping WAV files to XWM(A) with the xWMAEncode command line utility (from the DX SDK of June 2010), but as soon as I play back the XWM file in a looping audio buffer, I notice a significantly noticable silence before it loops over.

I found out that when filling an XAudio2 audio buffer manually with a synthesized vibrato sound, no looping bug occurs. To further support this, I decoded the XWM file back into WAV, and the WAV file had exactly the same amount of silence at the end as I noticed in the playback, which turns out to be of 0,06 seconds length:

My first question is if anyone noticed the same behavior of the xWMAEncode utility, and if it is either a bug of the utility or even of the XWMA format itself.

I'd love to know some workaround for this if it can't be fixed by the encoding of the WAV itself.

I thought of setting the LoopLength sample of the audio buffer to exactly before the silence occurs. But for that I'd need to pray that such a silence isn't dynamic depending on the sample rate. Has anyone fixed it like this before and can provide or link me to details about this?

Head-shaking corner: MP3 adds silence to the start of each file, so XWM likes to put it at the end? Do we live in times were only OGG gets stuff looping correctly?


texts: LibGdx ImageButton in table not clicking

texts:
i'm having a problem adding ImageButtons to a Table in libGDX. The buttons seem to work fine when i add them directly to the stage, i can click on them, and they change textures and do whatever they are suppossed to. However, when i add them to a table, and then add the table to the stage, i can't click on them for some reason.

This is how i'm creating a button (aButton is an ImageButton which i declared preivously)

public void configAButton(Texture pressedTexture,Texture notPressedTexture)
{
Skin skin = new Skin();
skin.add("button_down", pressedTexture);
skin.add("button_up", notPressedTexture);
ImageButton.ImageButtonStyle buttonStyle = new ImageButton.ImageButtonStyle();
buttonStyle.imageUp = skin.getDrawable("button_up");
buttonStyle.imageDown = skin.getDrawable("button_down");
aButton = new ImageButton(buttonStyle);

}

i use that method in "show()", and once i've done that i create my table like

 userInterfaceTable = new Table();
 userInterfaceTable.setWidth(stage.getWidth());
 userInterfaceTable.align(Align.bottomRight);

i just add the button to the table

userInterfaceTable.add(aButton).size(60,60).padRight(30);

And add the table to the stage

stage.addActor(userInterfaceTable);

what am i missing? thanks in advance, i'm quite new to this.


texts:
I have this GUI to graphically display a variable similar to the health in a game. The variable 'test' goes up and down during gameplay.

To show this I have the following onGUI ():

public GUISkin btnskin1;
public Texture2D emptyTex;
public Texture2D fullTex;
public Vector2 pos = new Vector2(20,40);
public Vector2 size = new Vector2(60,20);

void OnGUI()
{
    float test;

    GUI.skin = btnskin1;

    if (LoadDiagram.diagramaCarga.TryGetValue (TimeManager.gametime, out test))
    {
        GUI.BeginGroup (new Rect (pos.x, pos.y, size.x, size.y));
        GUI.Box (new Rect (0, 0, size.x, size.y), emptyTex);

        //draw the filled-in part:
        GUI.BeginGroup (new Rect (0, 0, size.x * test, size.y));
        GUI.Box (new Rect (0, 0, size.x, size.y), fullTex);
        GUI.EndGroup ();
        GUI.EndGroup ();
    }
}

In the game scene I attached the empty bar to the emptyTex texture, and the full bar to the fullTex texture. When I play the game, he bar is always full. I have not inserted the minimum and maximum of the variable test because I don't know where, but I guess that may be necessary.

Any hints?


texts: Is there a build-in function to count the amount of sprites drawn by SpriteBatch per frame?

texts:
I'm hoping to find out how many sprites are on the screen at any given time.

In other words, is it possible to find out how many times spriteBatch.Draw();
is called between spriteBatch.Begin(); and spriteBatch.End();?

I'm looking for a build-in function. Although I'm more then happy to write something myself, I'd rather not reinvent the wheel, and maybe I've overlooked something.


texts: Creating rectangles from the inner part of a texture2D

texts:
This may be hard to understand, but I'll do my best.

You will see that the first image is a normal Mario, and the other is the result I am looking for. I'm trying to find a way to extract rectangles (biggest possible to smallest) from a texture2D, without overlapping rectangles. If the pixel is completely transparent, leave it out of the loop. I know it would be really easy to implement a rectangle for every pixel, but millions of rectangles isn't going to help performance wise. The goal is to get rectangles somewhat like this, decreasing the total rectangles greatly.

Any ideas or links? Anything would be great.


texts: What's wrong with my food generating code?

texts:
This script is intended to produce amount of (food) objects for the players over the network. What should happen is that when a player eats one food, another food object gets created in another random place. Somehow it doesn't do that.

Here's the script.

 public class FoodManager : Photon.MonoBehaviour {

 [SerializeField] GameObject smallCirclePrefab;
 [SerializeField] float widthOfBoard = 100;
 [SerializeField] float heightOfBoard = 100;
 [SerializeField] int amtOfSmallCircle = 100;
 [SerializeField] int sizeOfCircle = 5;
 // Use this for initialization
 void Start()
 {
    if(PhotonNetwork.isMasterClient)
    produceSmallCircle(amtOfSmallCircle);
 }
 // Update is called once per frame
 void Update()
 {
 }
 void produceSmallCircle(int n)
 {
     Vector2 position;
     GameObject circle;
     float positionX, positionY;
     int ratioOfSize = 5;
     for (int i = 0; i < n; i++)
     {
         positionX = Random.Range(-widthOfBoard / 2, widthOfBoard / 2);
         positionY = Random.Range(-heightOfBoard / 2, heightOfBoard / 2);
         position = new Vector3(positionX, positionY,0);
         circle = PhotonNetwork.InstantiateSceneObject(smallCirclePrefab.name, position, transform.rotation, 0,null) as GameObject;
         circle.transform.localScale = new Vector3((float)sizeOfCircle / ratioOfSize, (float)sizeOfCircle / ratioOfSize, (float)sizeOfCircle / ratioOfSize);
     }
 }

 }

and here's the other script

 using UnityEngine; using System.Collections;

 public class FoodCollision : Photon.MonoBehaviour {

 public static float amtOfIncreaseSpeed = 1f;
 public static float amtOfIncreaseHealth = 1f;
 public static float ratioOfSpeed = 150.0f;
 public static float increaseSize = 0.001f;
 PhotonView photonView;
 BoxCollider2D boxCollider;
 SpriteRenderer sp;
 void Awake()
 {
     photonView = PhotonView.Get(this);
     boxCollider = GetComponent<BoxCollider2D>();
     sp = GetComponent<SpriteRenderer>();
 }
 // Use this for initialization
 void Start()
 {
 }
 // Update is called once per frame
 void Update()
 {
 }
 public void DestroyGO()
 {

     photonView.ownerId = PhotonNetwork.player.ID;
     boxCollider.enabled = false;
     sp.enabled = false;
     photonView.RPC("DestroyRPC", PhotonTargets.MasterClient);

 }
 [PunRPC]
 void DestroyRPC()
 {
     PhotonNetwork.Destroy(gameObject);
 }

 }


texts: How do I randomly create and store enemy data for my iPhone game?

texts: In my game you need to protect something from enemies. There can be many on the screen at once. But I don't know how to create the enemies randomly, and how I can save the data to each enemy? Can give good tips or good links to tutorials?


texts: Object orientated design for RPG character creation

texts:
This question may not be helpful to some but I'll ask anyway. I've hit a bit of a object orientated design issue. Making a RPG and the user gets to choose their own class i.e warrior/rogue/etc.

Sample:

int main()
{
    CharacterP *cPntr = new CharacterP // creates base pointer
    cPntr->createClass(cPntr, "Warrior"); // creates a new Warrior object which cPntr is now
                                           //pointing to.

    cPntr->printCharacterName();  //will print the warriors print name function

    return 0;
};

class CharacterP
{
    void createClass(CharacterP* &samp, string choice)
    {
        if (choice == "Warrior")
            samp = new Warrior;
         // other classes go here...... i.e Rogue, Mage
    }

    virtual void printCharacterName() //I don't want this function here
                                      //as this function will never be used, however it is
                                      //needed as the type of pointer for cPntr is CharacterP
                                      //which is the base of warrior.
    {
        std:: cout << "i don't want this function here, although it is required;
    }

};

class Warrior : public CharacterP
{
    virtual void printCharacterName()
    {
        std::cout << "you printed warrior";
    }
};

The main problem is the way I've designed this: If I want to use a Warrior function, I also have to define it into the base class CharacterP. When i start branching this out and adding more classes i.e Mage/rogue its going to be a maintenance nightmare as the base class would have a lot of functions that won't be used at all.

Questions:

Why does this happen?

Why does the base class also need to have the same function even though the derived function is virtual?

What is a more efficient way of doing what i am doing? (giving the user
the ability to create any classes they want i.e Warrior,Warrior,Mage/Rogue,Mage,Mage) maybe a way to create a warrior object with its own pointer which can be repeated so 3 warrior objects are created and can be used at runtime.


texts: How do I properly use particle simulation in Unity?

texts:
So I'm using Unity's simulate function to pre-render particles. It seems that simulate is not quite working as to what I expect. It's most likely a setting that I missed. But I just really cannot find the issue.

This is from inside the editor, I clicked on the particle object and just let it run. This is what I'd like.

This is after I've run the game a little bit, then hit pause. This is what is currently happening, for some reason the particles get bigger.

Here is the script that I've attached.

public float initTime;
public ParticleEmitter partEmitter;
// Use this for initialization
void Start () {
    for (float i = 0.1f; i < initTime; i = i + 0.1f) {
        partEmitter.Simulate(i);
    }
}

I've run this scene in both Unity 3.5 and in Unity 4.0. Same thing happens in both versions.I'm pretty sure that it's something to do with the script. But I've tried many different pieces of code and they are all similar and do the same thing.


texts: Handling creation of entities on level creation

texts:
I'm currently working on a 2d physics based plat former, kinda in the style of super meat boy. In super meat boy, you have multiple levels and I want a similar sort of thing but is there a general way of handling creating entities at the start of a level. Since I'm using an entity-component design and using tiled editor to load levels (and even lua script do to some more config/level related logic), how would I handle creating entities?

Currently, I parse my tiled xml map and do something like

if("MovingPlatform"){
   createMovingPlatform(mapObject)
}elseif("SomeOtherEntity"){

} //... so on so forth

But this will soon become a really long branch of if statements just to load my entities. Is there a cleaner design pattern or way of doing this. I was thinking to use a map or strings to classes that create that entity like so:

 //in constructor of level loader
 entityCreatorMap["MovingPlatform"] = MovingPlatformEntityLoader()

//somewhere later creating my entities by parsing xml
entityCreatorMap[mapObject.getName()].create(mapObject)

But that will be lots of lines initialising these kind of objects. Any ideas?


texts:
I am trying to create my own game in java  (without OpenGL, LWJGL etc) and I am having a problem with the rendering.
My map is pretty big and the game redering the entire map at once which cause a result of 2 fps.
Does anyone know how I can make my game to render only what the player see and not the entire map?
map loading code:
private void loadMap(BufferedImage image) {
    int w = image.getWidth();
    int h = image.getHeight();

    for(int i = 0; i<w; i++) {
        for(int j = 0; j<h; j++) {
            int pixel = image.getRGB(i, j);
            int red = (pixel >> 16) & 0xff;
            int green = (pixel >> 8) & 0xff;
            int blue = (pixel) & 0xff;

            if(red >=250)
                handler.addObject(new Wall(i*32, j*32, ID.Wall));

            if(green==255)
                handler.addObject(new Floor(i*32, j*32, ID.Floor));
        }
    }
}

camera code:
public void tick(GameObject object) {

    x += ((object.getX()-x)-Game.WIDTH/2)*0.05f;
    y += ((object.getY()-y)-Game.WIDTH/2)*0.05f;

}

    g2d.translate(-camera.getX(), -camera.getY());
    handler.render(g);
    maps.render(g);
    g2d.translate(camera.getX(), camera.getY());

more codes for MCVE:
public synchronized void start() {
    thread = new Thread(this);
    thread.start();
    running = true;
}

public synchronized void stop() {
    try {
        thread.join();
    } catch (InterruptedException e) {
                e.printStackTrace();
    }
}

public void run() {
     long lastTime = System.nanoTime();
        double amountOfTicks = 60.0;
        double ns = 1000000000 / amountOfTicks;
        double delta = 0;
        long timer = System.currentTimeMillis();
        int frames = 0 ;
        while (running) {
            long now = System.nanoTime();
            delta += (now - lastTime) / ns;
            lastTime = now;
            while (delta >= 1) {
                tick();
                delta--;
            }
            if(running)
                render();
            frames++;

            if(System.currentTimeMillis() - timer > 1000) {
                timer += 1000;
                System.out.println("FPS: " + frames);
                frames = 0;
            }
        }
        stop();
}

public void tick(){
    for(int i = 0; i<handler.objects.size(); i++) {
        if(handler.objects.get(i).getId() ==ID.Player) {
            camera.tick(handler.objects.get(i));
            hud.tick();
        }
    }
}

public class Window extends Canvas{

    private static final long serialVersionUID = -6357664197674207224L;

    public Window(int width, int height, String title, Game game) {
        JFrame frame = new JFrame(title);

        frame.setPreferredSize(new Dimension(width, height));
        frame.setMinimumSize(new Dimension(width, height));
        frame.setMaximumSize(new Dimension(width, height));

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.add(game);
        frame.setVisible(true);
        game.start();
    }
}

public static void main(String[]args) {
    new Game();
}

public void render() {
    BufferStrategy bs = this.getBufferStrategy();
    if(bs == null) {
        this.createBufferStrategy(3);
        return;
    }
    Graphics g = bs.getDrawGraphics();
    Graphics2D g2d = (Graphics2D) g;
    g.setColor(Color.black);
    g.fillRect(0, 0, WIDTH, HEIGHT);
    //GameState

    //////////////////////////////////////////
    if(GameState == STATE.game) {
    g2d.translate(-camera.getX(), -camera.getY());
    handler.render(g);
    g2d.translate(camera.getX(), camera.getY());
    hud.render(g);
    }


texts: Stress testing a game server without users?

texts:
I'm working on a card game and its server. There will be a lobby with many tables and many players. The only issue is, how can I see how it might handle 100's of concurrent users without hundreds of concurrent users?

How is this sort of thing usually done?


texts:
I'm trying to draw "bullets" in my game, but I think something is wrong with velocity computation. Sometimes the "bullets" are going in the right way, but sometimes they won't. The CameraFront is constructed with euler angles. Can you help? Thanks in advance
So this is how I create bullets:
Bullet_tracer makeBulletTracer(v3 cameraFront,v3 startP, v3 endP)
{

    Bullet_tracer result = {};

    //assert((gTracersCount + 1) <= MAX_BULLET_TRACERS);

    mat4 model = indentity();
    model = scale(model, v3(.5f,.5f,1.5f));
    v3 up = v3(0.0f,1.0f,0.0f);
    v3 right = normalize(cross(cameraFront,up));
    mat4 M = rows3x3(right,up,cameraFront);
    model = model * M;
    model = translate(model, startP + v3(0.0f,3.0f,0.0f));
    result.model = model;
    result.velocity = cameraFront;
    gTracersCount++;
    return result;
}

This is how I draw them:
for (u32 tracerIndex = 0; tracerIndex < gTracersCount; tracerIndex++)
{
    Bullet_tracer *tracer = gameState->tracers + tracerIndex;

    v3 p = getTranslationPart(tracer->model);
     v3 offset = (p + tracer->velocity) * input->dtForFrame * 0.01f;
    tracer->model = translate(tracer->model, offset);

    passUniformMatrix(opengl.shaderProgram,tracer->model,false,"model");
    glDrawArrays(GL_TRIANGLES, 0, 36);
}


texts: Enable and disable different component on a Gameobject

texts:
So far I am not clear how do you actually access the various components on a game object, to enable and disable them.

I have a component that has various scripts and elements, like a camera, transform, audio listener and few other custom scripts.

It is in the scene, so I try to access to it via script:

private GameObject _player;

_player = GameObject.Find("the_player")

So far so good; if I want to access for example to the camera, and enable or disable it, I can do it

    _player.GetComponent<Camera>().enabled = true;

This disable correctly the camera, or eanble it, depending from the paramenter that I pass.

Now, if I want to access my script, called "playerscript"; I can't do the same thing, since I get an error:

    _player.GetComponent<playerscript>().enabled = true;

Not sure why I get an error; I have a class that is called "playerscript", that is attached to that _player object, but instead, VS complain.

This is the error message:

Error   CS0246  The type or namespace name 'playerscript' could not be found (are you missing a using directive or an assembly reference?)

I did try to use also GetComponentInChildren, but the result is the same.

If I have the object _player, which hold a reference to the original game object instantiated in the scene, why I can't simply access all the elements attached to it, via GetComponent and dot notation? I believe this used to work time ago, but in Unity5 I can't get this to work.

EDIT: This is the content of the playerscript class:

using UnityEngine;
using System.Collections;

public class playerscript : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        // get the instance of the button from UI manager
    }

    void OnTriggerEnter(Collider world_item)
    {
        //enable item animation
    }

    void OnTriggerExit(Collider world_item)
    {
        //disable item animation
    }
}


texts: how to set volume of sound depending on the impulse a body receives in Libgdx / Box2d?

texts:
I am trying to set the volume of a bouncing sound of a ball depending on how hard the ball hits something. so the harder the ball hits a wall or a ground the more loud the bounce sound.
I couldn't find anyway to get the impulse of a body other than the postSolve(Contact contact, ContactImpulse impulse)  method inContactListner class.
But i then realized that unlike the beginContact(Contact contact) method, postSolve(Contact contact, ContactImpulse impulse)  gets called repeatedly until the contact ends. so it repeatedly plays the bouncing sound making it sound stalked and buggy.
I cant use the beginContact(Contact contact) method because there is no way to get the impulse that the ball is receiving from this method. I tried to to use the velocity of the ball instead of impulse inside beginContact(Contact contact)but that didnt yield good results and found it very complicated as i had to consider both horizontal and vertical speeds.
so my question is how can I make the sound play only once if i am using the postSolve(Contact contact, ContactImpulse impulse)  method or is there any other solution to achieve what i am trying to do here?


texts: What are some good resources for learning HLSL?

texts:
The last time I tried learning HLSL, I made a few shaders and mostly understood what I was doing, but I still felt like I was stumbling in the dark. Most of what I learned I got from various blog posts that didn't explain things very well.

Also, the documentation on MSDN seems to be more of a function reference.

Where can I learn to not only write HLSL, but learn techniques for writing shaders?


texts: How do I get a Halo component and change its color?

texts:
I have a Halo component on an object, on the same object I have a script, in the script I tried to get the Halo component, but GetComponent<Halo>() doesn't work, it says that it can't be found.

My question is, how can I get the Halo component and change the color of it?


texts: Shooting function in pygame w/ 2 Players

texts:
I'm trying to program a shooting function in my game using pygame. Process:

Player one will press 'Space' and shoot their type of projectile
Player two would press 'E' and shoot their type of projectile
Player one's projectile would collide with player two but not player one (and vice versa).

I'm not sure how to code this function properly. Here's my code so far:

Initalize
import pygame, math
WHITE = (255, 255, 255)
#Creating sprites

class Player(pygame.sprite.Sprite):

    def __init__(self, color, width, height):

        super().__init__()
        #Config
        self.image = pygame.Surface([width, height])
        self.image.fill(WHITE)
        self.image.set_colorkey(WHITE)

        # Draw
        pygame.draw.rect(self.image, color, [0, 0, width, height])

        # Fetch
        self.rect = self.image.get_rect()

    def right(self, pixels):
        self.rect.x += pixels
    def left(self, pixels):
        self.rect.x -= pixels
    def up(self, pixels):
        self.rect.y -= pixels
    def down(self, pixels):
        self.rect.y += pixels

pygame.init()
# Config
RED = ( 255, 0, 0)
BLUE = ( 43, 255, 230)
ORANGE = ( 255, 170, 0)
BLACK = (0, 0, 0)

SCREENWIDTH = 400
SCREENHEIGHT = 500

size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Squares Fight")

group1 = pygame.sprite.Group()

player1 = Player(BLUE, 50, 50)
player2 = Player(ORANGE, 50, 50)
player1.rect.x = 5
player1.rect.y = 5
player2.rect.x = 345
player2.rect.y = 445

group1.add(player1, player2)

loop = True
startend = False
startanew = True
clock = pygame.time.Clock()
font = pygame.font.SysFont("berlinsansfb", 72)
text = font.render("Fight!", True, WHITE)

# Game Loop
while loop:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        loop = False

        #Logic
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
                player1.left(3)
        if keys[pygame.K_RIGHT]:
                player1.right(3)
        if keys[pygame.K_UP]:
                player1.up(3)
        if keys[pygame.K_DOWN]:
                player1.down(3)
        if keys[pygame.K_a]:
                player2.left(3)
        if keys[pygame.K_d]:
                player2.right(3)
        if keys[pygame.K_w]:
               player2.up(3)
        if keys[pygame.K_s]:
               player2.down(3)

    collision = pygame.sprite.collide_rect(player1, player2)
    if collision == True:
            group1.remove(player1, player2)
            startend = True
    group1.update()
    if startend == True:
            pygame.display.set_caption("They destroyed eachother! Press space to do it again")
            startanew = True
    if startanew == True and keys[pygame.K_SPACE]:
            group1.add(player1, player2)
            pygame.display.set_caption("Squares Fight")
            startend = False
    # Drawing
    screen.fill(BLACK)
    screen.blit(text,
                (200 - text.get_width() // 2, 240 - text.get_height() // 2))
    group1.draw(screen)

    # Closing
    pygame.display.flip()
    clock.tick(60)
    #Indentation isnt right because how i needed to format this
 pygame.quit()

What else do I need to add to accomplish this task?


texts: Finding shapes in 2D Array, then optimising

texts:
I've just been allowed an image...The image below from my game shows some darkened blocks, which have been recognised as being part of a "T" shape.  As can be seen, the code has darkened the blocks with the red spots, and not seen the "T" shapes with the green outlines.

My code loops through x/y, marks blocks as used, rotates the shape, repeats, changes colour, repeats.

I have started trying to fix this checking with great trepidation.  The current idea is to:

loop through the grid and make note of all pattern occurrences (NOT marking blocks as used), and putting these to an array
loop through the grid again, this time noting which blocks are occupied by which patterns, and therefore which are occupied by multiple patterns.
looping through the grid again, this time noting which patterns
obstruct which patterns

That much feels right... What do I do now?

I think I would have to

try various combinations of conflicting shapes, starting with those
that obstruct the most other patterns first.How do I approach this one?
use the rational that says I have 3 conflicting shapes occupying 8 blocks, and the shapes are 4 blocks each, therefore I can only have a maximum of two shapes.

(I also intend to incorporate other shapes, and there will probably be score weighting which will need to be considered when going through the conflicting shapes, but that can be another day)

I don't think it's a bin packing problem, but I'm not sure what to look for.  Hope that makes sense, thanks for your help

EDIT Despite clarity of question, everyone seems to have understood, yes,

I want to find the maximum "T" shapes within each colour

(because if I gave you points for two and you had made three, you'd be a bit annoyed)


texts:
I'm trying to achieve multiple lights shadows. Currently my program works using only 1 spotlight as a light source that produces shadows. Well... I want to involve multiple lights to give a more realistic effect to my scene.

However, I'm facing a scenario which is a little bit unclear for me:

The steps I follow to create shadows is

a) Create FBO

b) Render scene from light's perspective using a depth texture attached to my FBO

c) Render the scene normally, using my texture from my FBO as a shadowmap texture in order to be able to sample it and creating finally shadows.
The steps I follow to create multiple shadows is

a) Create FBO1 and FBO2

b) Render scene from 1st light's perspective using a depth texture attached to my FBO1

c) Render the scene normally, using my texture from my FBO1 as a shadowmap texture in order to be able to sample it and creating finally shadows.

d) Render scene from 2nd light's perspective using a depth texture attached to my FBO2

e) Render the scene normally, using my texture from my FBO2 as a shadowmap texture in order to be able to sample it and creating finally shadows.

Now, the step 1) is pretty clear, works fine. When I manage to implement step 2), something happens: the shadows rendered will be the shadows of my last light (depending the order I call rendering methods). So in this case I get shadows only from my 2nd light.

If I reverse the order of calls (this order: a -> d -> e -> b -> c) and render first in my second FBO and then in my first FBO I get the shadows from my first light source. So basically I conclude: my shadows are not working simultaneously.

Is this the correct approach? (I've seen a solution which uses in fragment shader an array of shadowMaps, an array of lightSpace coordinates so this involves multiple uniforms... what do you think about this?)

Thanks


texts: Why do most racing games have tracks that are closed loops?

texts: In most racing games (Mario Kart, Sega Rally, F-Zero, etc.), racers typically make some number of laps in a closed circuit.  The most notable exceptions that come to mind are all arcade games, or arguably not even a racing game (Trackmania, OutRun, the Cruis'n series).  Why would a designer want to build tracks as closed loops, and why is it so commonplace?


texts: How can I display the visible number of health?

texts:
I'm trying to create health that is just numbers, I know how to do the bar but I just want it to show.

Here is the gml you need to see

plvl = 1;

mphlth = 75 + (plvl * 25);

phlth = 100
if (phlth >= mphlth) {
    phlth = mphlth
}
draw_text(10,10,string(phlth));

I also tried with the following:

draw_text(10,30,"health: "+string(player1.phlth));

Is there anyway to display the health number?


texts: How to efficiently store a large amount of data?

texts:
I am doing minecraft-like game. I have a limited world in size 32x16x32 chunk. Each chunk is a structure in which there is a three-dimensional array containing the values of the blocks located in it. Structures and arrays are so arranged that from world coordinates I can get the block number that I need and its value. When you start the program, the world is generated, but I need to save all these block values in a file so that when the world changes, these changes are saved after exiting the program. How do I need to organize the recording of data chunks to a file so that it is productive and economical in terms of memory occupied?

Let structures and arrays be declared as
c [32] [16] [32] - structures
int block_id [16] [16] [16] - block id


texts: How can I convert a 2D bitmap (Used for terrain) to a 2D polygon mesh for collision?

texts:
So I'm making an artillery type game, sort of similar to Worms with all the usual stuff like destructible terrain etc... and while I could use per-pixel collision that doesn't give me collision normals or anything like that. Converting it all to a mesh would also mean I could use an existing physics library, which would be better than anything I can make by myself.

I've seen people mention doing this by using Marching Squares to get contours in the bitmap, but I can't find anything which mentions how to turn these into a mesh (Unless it refers to a 3D mesh with contour lines defining different heights, which is NOT what I want). At the moment I can get a basic Marching Squares contour which looks something like this (Where the grid-like lines in the background would be the Marching Squares 'cells'):

That needs to be interpolated to get a smoother, more accurate result but that's the general idea. I had a couple ideas for how to turn this into a mesh, but many of them wouldn't work in certain cases, and the one which I thought would work perfectly has turned out to be very slow and I've not even finished it yet! Ideally I'd like whatever I end up using to be fast enough to do every frame for cases such as rapidly-firing weapons, or digging tools.

I'm thinking there must be some kind of existing algorithm/technique for turning something like this into a mesh, but I can't seem to find anything. I've looked at some things like Delaunay Triangulation, but as far as I can tell that won't correctly handle concave shapes like the above example, and also wouldn't account for holes within the terrain.

I'll go through the technique I came up with for comparison and I guess I'll see if anyone has a better idea. First of all interpolate the Marching Squares contour lines, creating vertices from the line ends, and getting vertices where lines cross cell edges (Important). Then, for each cell containing vertices create polygons by using 2 vertices, and a cell corner as the 3rd vertex (Probably the closest corner).

Do this for each cell and I think you should have a mesh which accurately represents the original bitmap (Though there will only be polygons at the edges of the bitmap, and large filled in areas in between will be empty). The only problem with this is that it involves lopping through every pixel once for the initial Marching Squares, then looping through every cell (image height + 1 x image width + 1) at least twice, which ends up being really slow for any decently sized image...


texts: How does SDL2 renderer work? Does it make sense to render to only part of a window?

texts:
In order to run a game without using the CPU/GPU too much, I want to only update the section of the window that has changed.

Does this goal even make sense? How does the texture objects/renderer work when updating the screen? My idea is that the renderer builds a matrix of ints (pixel colours) and when SDL_RenderPresent is called, this edits a matrix stored on the memory that controls the colours for each pixel on the screen.

If what I've said so far makes sense, then is my implementation below correct (not updating more of the screen than needed)? I've tried to keep my code very, very simple so that it's easy to read.

The programme jumps the character (picture of a prince) from the top-left of the window to the bottom-left, and visa-versa, whenever the user inputs anything. This is just to keep the code simple for the example.

#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

using namespace std;

int main ()
{
    // Screen dimension constants
    const int WINDOW_WIDTH = 639;
    const int WINDOW_HEIGHT = 1015;

    const int PRINCE_WIDTH = 74;
    const int PRINCE_HEIGHT = 114;

    SDL_Init ( SDL_INIT_EVERYTHING );

    SDL_Window * window =
    SDL_CreateWindow ( "example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN );

    SDL_Renderer * renderer = SDL_CreateRenderer ( window, -1, SDL_RENDERER_ACCELERATED );

    SDL_Texture * background = IMG_LoadTexture ( renderer, "./images/background.bmp" );
    SDL_Rect rect_background = { 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT };
    SDL_RenderCopy ( renderer, background, & rect_background, & rect_background );

    const SDL_Rect rect_place_one = { 400, 600, PRINCE_WIDTH, PRINCE_HEIGHT };
    const SDL_Rect rect_place_two = { 40, 60, PRINCE_WIDTH, PRINCE_HEIGHT };

    SDL_Texture * prince = IMG_LoadTexture ( renderer, "./images/prince.bmp" );
    SDL_RenderCopy ( renderer, prince, NULL, & rect_place_one );
    SDL_RenderPresent ( renderer );

    SDL_Event input;

    for ( uint8_t count = 0; SDL_WaitEvent( & input ); ++count )
    {
        // User requests quit
        if ( input.type == SDL_QUIT )
            break;

        if ( input.type != SDL_KEYDOWN )
            continue;

        if ( ( count % 2 ) )
        {
            SDL_RenderCopy ( renderer, prince, NULL, & rect_place_one );
            SDL_RenderCopy ( renderer, background, & rect_place_two, & rect_place_two );
        }
        else
        {
            SDL_RenderCopy ( renderer, prince, NULL, & rect_place_two );
            SDL_RenderCopy ( renderer, background, & rect_place_one, & rect_place_one );
        }

        SDL_RenderPresent ( renderer );
    }

    SDL_DestroyTexture ( prince );
    SDL_DestroyTexture ( background );
    SDL_RenderClear (renderer);
    SDL_DestroyWindow ( window );
    SDL_Quit ();

    return 0;
 }


texts:
I've been making a game to learn unity and I have been using the free look cam that comes default but have encountered a problem that I don't know how to fix. Basically the camera rig isn't following the target very well, it follows really far behind the target and I have turned up the move speed, messed with other settings but no luck.

Help please!


texts: How to have 3d multiple planet gravity in unity c#?

texts: Im using unity and I want to make a game where you can walk around small planets and the further away you get, the weaker the gravity, so you can go to other planets. All the tutorials so far only work with one planet, how do I code this? Is there anything I can download that does it for me?


texts: Unity creating 3d clothes for game character

texts:
I am trying to make a system where players can change out their clothes with others if they like, and even layer up clothes such as covering a shirt with a jacket, then an armored vest. I have ran into a problem with the body parts of the player clipping through the clothes.

For more information on what I tried and what others have told me refer to:

https://blenderartists.org/t/trying-to-get-changeable-clothes-to-work/1171090

The best solution I like the most is:

"If you can get away with hiding parts of the skin (like the armpits), then do so.

You can also load mask textures onto your body to clip fragments/pixels in the shader, depending on the state of the clothing, so that your armpits are only invisible when wearing a hoodie, not when wearing a tank top.

Otherwise, the best technique I’ve found to eliminate body/clothing clipping, on a body with autoweights, is to use a vertex weight proximity to blend between data transfer weights (from body, for tight sections) and autoweights (for loose sections)."

The problem is I have no Idea how to implement this in blender and unity.

Any help is appreciated.


texts: How to retain gameobject in DoNotDestory objects when game is restart

texts:
I have an empty object which is not destroy after the game is restarted.
DontDestroyOnLoad(this.gameObject);

I have some gameobject references in the script
public GameObject leaderboardPanel;
public GameObject addPointsPanel;
public GameObject updateButton;

When the scene is reloaded then all the above objects in inspector shows
Missing(GameObject)

after game is reloaded


texts: How to apply outer glow to a UI game object? Shader? Particle?

texts:
What's the best or easiest approach to apply an outer glow effect to a UI game object -- let's say, a popup dialog, so it's a rectangular shape -- in Unity 2018.3?

Is this something that should be done with a shader, or is it a particle effect?

Ideally I should be able to specify and perhaps even dynamically adjust the color and size of the glow.

Edit: image below shows a blue rectangle, which has this subtle, grey glow around it. I'm hoping to generate this glow effect somehow in Unity.


texts: FullSerializer Update serialized property name

texts:
Currently we have some ScriptableObjects that are referenced by their name. This comes with some issues as names may change and also they don't have to be unique. We would like to switch to UUIDs.
using FullSerializer;

[System.Serializable]
[fsObject(Converter = typeof(CharacterDataConverter))]
public class CharacterData
{
  public CharacterSO player;
  public CharacterSO mentor;
}

The mentor field is currently serialized as mentorName. With the changes the serialized field name would be mentorUid. This is handled by the CharacterDataConverter, but this has to be updated all the time when CharacterData class changes and is often forgotten.
Much simpler would be to use fsProperty:
using FullSerializer;

[System.Serializable]
public class CharacterData
{
  [fsProperty(Converter = typeof(PlayerConverter)]
  public CharacterSO player;
  [fsProperty(Converter= typeof(CharacterSOConverter), Name="mentorName")]
  public CharacterSO mentor;
}

But this can handle only either mentorName or mentorUid.
Is there another solution? Maybe using versioning?


texts: How to handle multiplayer in JavaScript?

texts:
I'm just doing a bit of research into tech to use for a mobile multi-player game.

It's more an experiment at present so for the moment, the only thing that Players need to be aware of is the other Players.

If this was a typical web application and not a game It'd just have HTTP requests firing all the time -- but since this is a game, performance and accuracy is going to be a problem.

Due to the game being targeted at multiple phone platforms, lets say that the client will be written in JavaScript or a framework based on JavaScript. The server technology is totally open.

Each player will need to make the equivalent of a HTTP post and get only using a faster protocol. The reason for multiplayer being web based is because multiplayer across Bluetooth or other local networking would be too diverse across the platforms and could cause problems.

So the question boils down to whats a good protocol/technology to use for JavaScript multiplayer? Any advice on the server side stuff or does it matter? Any reason I should drop this two-tier architecture and go with direct phone-to-phone connection?


texts:
i have fair experience with java game programming,
i already made a simple mario game (side-Scrolling)
i'm wondering how can i make a "Java" Game like that

http://www.youtube.com/watch?v=utwtXEYW1L0
or that
http://www.youtube.com/watch?v=uqz4dunlhX4
the main problem is that i don't know how to make a 2D game looks like 3D
i just need a tutorial or the idea behind such things.
Thanks in Advance :)


texts: Should I use SAX or DOM to parse Game dialogue/text events in XML?

texts:
I'm planning to put all my text dialogue/events in an XML file and then use either SAX or DOM parser in Java to retrieve the correct text.

I'm intending for there to be A LOT of text in this game, so which parser would make more sense to use?

I know SAX has to go through the whole document and I need the text to be retrieved more or less immediately while a DOM parser needs to store the DOM in memory and, as I said, I'm going to have a lot of text in it, plus the rest of the game requires memory too.

I'm developing for PC. Which parser would generally make more sense to use?


texts: Vuforia AR/VR sample with Google Cardboard SDK: I cannot switch from augmented reality to virtual reality

texts:
I have followed the Integrating Cardboard to the AR/VR Sample latest tutorial. I have configured the provided scene sample according to that tutorial. I have compiled it to Android without any problem.

The game load an AR scene with a yellow pointer in the center. If I understood well, if a glaze at the ImageTargetStones GameObject, it will switch to VR. Unfortunately I cannot find that GameObject anywhere. I only see the AR scene with nothing than the yellow pointer.

I don't find what I'm missing. Why is not that ImageTargetStones GameObject in the AR scene?

UPDATE 1

I think I want to use Vuforia for an uncommon use. I think that's a reason of a possible misunderstanding.

I don't want to use its image recognition possibilities. I want to switch between AR to VR when glazing to a button.

I have tried to duplicate the VRButton to move it to an independent place of the scene with no parent. I have checked its IsTrigger checkbox. I have added a PointerEnter EventTrigger that set Focused to true. I have added a PhysicsRaycaster to both AR Camera and MainCamera (child of CardboardMain-Head).

Nothing happens when I gaze at the button. I have to compile everytime I want to try it by the way. I did not manage to make it work in the editor.

UPDATE 2

I haven't been able to do it with vuforia yet. I have done it with WebCamTexture. Specifically, I have used the scripts of this answer: http://answers.unity3d.com/answers/687987/view.html . The result is not nice because the image from camera seems closer than it actually is (with Vuforia, there is not that problem)


texts: How can I render 3D dots at object vertex positions?

texts:
What is the best way to put a dot on a vertex?

I have a model (a plane for example) consisting of a few thousand vertices. I want to draw a red dot at every vertex's 3D position, just like 3ds Max's vertex selection mode, for example).

I've tried drawing a small line on each vertex location which works fine with few vertices, but it causes performance problems when I have large objects with many vertices. I've also tried doing this with a shader, but I can't get this to work (I want to highlight the selected vertices). I've thought about drawing a small 3D cube at every vertex location, but this seems terribly inefficient.

How can I accomplish this in a way that will scale to large scenes?


texts: How do/should MMOs handle disconnection during PvP?

texts:
In an MMO (not even necessarily an MMORPG) what are some techniques for dealing with players disconnecting in the middle of PvP?

In particular - how do you avoid adversely affecting people who get disconnected due to network (or even real-life) issues, while not adversely affecting those people that are engaging them?

And, importantly, how do you ensure that disconnecting cannot be used as a method of cheating?


texts: Calculate the extreme points of a quadrilateral

texts:
Given four points (a,b,c and d) how do I find the extreme points (b,d) from the perspective of the player (p).

I was trying to do it by finding the angle to the centre of the quadrilateral then checking for the furthest point either side but that obviously wouldn't work when the player is parallel to a point.

Any nudges in the right direction would be welcome.


texts: How can I render geometry represented in a 64-bit floating point environment?

texts:
In this video about Star Citizen, right at the 12:30 mark on the timeline you can see the player zooming in on a space station who's location is clearly out of the limit of 32-bit floating point numbers. As I understand it, in this game they're using 64-bit floating point precision for location calculations.

I'd like to implement something similar: an environment where objects are represented with 64-bit floating point precision, but which can still be rendered on 32-bit GPUs.

I do not understand how Star Citizen is able to render it in correct proportion with 32-bit GPUs since I've read that most GPUs run like 3x slower in double precision mode.

In other words how should I pass vertex positions and other rendering data accurately to the underlying rendering hardware? What should I do to the data to render it in 32 bit space? Or should I just use double precision GPUs?


texts: How to store character moves (sprite animations)?

texts:
So I'm thinking about making a small rpg, mainly to test out different design patterns I've been learning about. But the one question that I'm not too sure on how to approach is how to store an array of character moves in the best way possible.

So let's say I have arrays of different sprites.

This is how I'm thinking about implementing it:

array attack = new array (10);
array attack2 = new array(5);

(loop)
//blit some image
attack.push(imageInstance);
(end loop)

Now every time I want the animation I call on attack or attack2; is there a better structure?
The problem with this is let's say there are 100 different attacks, and a player can have up to 10 attacks equipped. So how do I tell which attack the user has; should I use a hash map?


texts: How to select top most gameObject in a stack of gameObjects?

texts:
I'm stuck trying to figure out how I can select the top most GameObject in a stack of GameObjects. In the picture below, I have a Green and Yellow circle stacked on top of each other. If I try to select the top most gameobject (the green one), it selects the yellow circle. Is there a way that I can make sure that when I go to select a circle, it selects the top most one? I'm currently using the OnMouseDown() function built into unity.

Update Sorting the colors on the z axis did not solve the problem. I'm still trying to figure out a solution


texts: Optimal way to create/spawn multiple sprites in mini2dx(subset of libgdx)

texts:
What is optimal way to spawn new sprites with different sizes in mini2dx(subset of libgdx)?
Currently I am maintaining ArrayList of enemy sprites

private ArrayList<Sprite> enemies = new ArrayList<Sprite>();

In the generateEnemies method:

private void generateEnemies() {
    // How many enemies to spawn max?? X
    for (int i=0; i<=5;i++) {
        float size = (float) Math.random() * 3;
        float speed = (float) Math.random() * 3;
        float y = (float )Math.random() * Gdx.graphics.getHeight();
        enemies.add(new Enemy(new Texture(Gdx.files.internal("gfx/enemy.png"))));
        enemies.get(i).setScale(size);
        enemies.get(i).setSpeed(speed);
        enemies.get(i).setPosition(0,  y);
    }
}

In render method:

for (int i = 0;i<=5;i++) {
    g.drawSprite(enemies.get(i), collisionPoint.getRenderX(),
    collisionPoint.getRenderY());
}

Although I seems to render the enemy but there is no control over the enemy sprite to respawn.
Is there any optimal way to do it?


texts: Shader / Reconstructing position from DEPTH in VR through Projection Matrix

texts:
In Unity you can access the Depth-Buffer in the Pixel Shader.
With that Depth-Buffer and the Nearplane, Farplane, CamToWorldMatrix and FOV you can calculate every pixel position of the objects the camera is seeing.

in VR though I get the wrong positions - because a VR frustum is slightly skewed. (http://doc-ok.org/?p=77)

So now we dont use the variables above to determine the Position -
Now should be using the Projection Matrix.

Unitys "OnRenderImage()" is rendering alternately left and right eye of the VR device. So we "take" the projection matrix from each different eye.
Also the FOV , Near and Far Planes, should be correct.
We have also the screen Resolution. - which is exactly "540x600"

The Big Question here:

How to get that pixel Position with the help of those values.?

This is working for non-VR for those who need this in a computeshader:

Script:

        computeShader.SetTexture(_Kernel, "_DepthTexture", depthRenderTexture);
        computeShader.SetFloat("_CamFOV", camFOV);
        computeShader.SetFloat("_CamAspect", camAspect);
        computeShader.SetFloat("_CamNear", camNear);
        computeShader.SetFloat("_CamFar", camFar);
        computeShader.SetFloat("_ScreenWidth", Camera.main.pixelWidth);
        computeShader.SetFloat("_ScreenHeight", Camera.main.pixelHeight);
        computeShader.SetVector("_CamWorldMatrix0", camWorldMatrix.GetRow(0));
        computeShader.SetVector("_CamWorldMatrix1", camWorldMatrix.GetRow(1));
        computeShader.SetVector("_CamWorldMatrix2", camWorldMatrix.GetRow(2));
        computeShader.SetVector("_CamWorldMatrix3", camWorldMatrix.GetRow(3));
        computeShader.Dispatch(_Kernel, (int)(Camera.main.pixelWidth*Camera.main.pixelHeight)/128, 1, 1);

ComputeShader:

    [numthreads(128, 1, 1)]
    void CSMain(uint3 id : SV_DispatchThreadID)
    {
        if (id.x >= (uint)(_ScreenWidth*_ScreenHeight))
        return;

        int y = id.x / int(_ScreenWidth);
        int x = id.x % int(_ScreenWidth);
        float4 depthInfo = _DepthTexture[uint2(x, y)];

        float depthValue = depthInfo.z * _CamFar;
        // world X and Y components of our target vector
        float tanFov = tan(radians(_CamFOV / 2));
        float screenDimY = tanFov * _CamNear;
        float screenDimX = screenDimY * _CamAspect;
        // normalize screenpos from range 0..1 to range -1..1
        float4 normPos = depthInfo * 2 - 1;
        float screenPosX = screenDimX * normPos.x;
        float screenPosY = screenDimY * normPos.y;
        float screenPosZ = -_CamNear;
        float4 objInEyeSpaceVector;
        objInEyeSpaceVector.xyz = float3(screenPosX, screenPosY, screenPosZ) * depthValue / _CamNear;
        objInEyeSpaceVector.w = 1;
        float4x4 camWorldMat = float4x4(_CamWorldMatrix0, _CamWorldMatrix1, _CamWorldMatrix2, _CamWorldMatrix3);
        float4 objInWorldSpace =  mul(camWorldMat, objInEyeSpaceVector);

}

^
but this has to work now in VR too.

There are already the answers for a unity-shader.
But i Need that as a computeshader

I dont have a v2f vert (appdata v) and a fixed4 frag (v2f i) : SV_Target in the compute shader. In the end of the day, i would like ... Input: Matrixes, floats, everything i Need incl. depth. I have already the current X and Y coordinate of the Screen-Pixel which gets rendered. So... the last line of Code should be: float4 pixelPositionWorld;
Just like in the first example i had.


texts:
Im new to nifty and Im trying to change text control using nifty in JME application following this tutorial.

Below is my TextRenderer code:

Element element = nifty.getScreen("loadlevel").findElementByName("loadingtext");
TextRenderer textRenderer = element.getRenderer(TextRenderer.class);
textRenderer.setText("loadingText");

Below is my nifty GUI code code for loadLevel scene:

<screen id="loadlevel" controller = "jmebase.TestLoadingScreen">
        <layer id="loadinglayer" childLayout="center" backgroundColor="#000000">
            <panel id = "loadingpanel" childLayout="vertical" align="center" valign="center" height="32px" width="70%">
                <control name="loadingbar" align="center" valign="center" width="100%" height="100%" />
                <control id="loadingtext" name="label" align="center"
                         text="                                                  "/>
            </panel>
        </layer>
    </screen>

I printed value of for both element and textRenderer. element is initialised properly but textRenderer object is null. I googled lot and lots of people got this issue but none provided appropriate solution. Anyone know how to fix it. Im really stuck need help.


texts: What are my tool options to prototype a 2D online multiplayer game?

texts:
I'm looking for the best tool to allow me to quickly put together a 2D game that relies largely on networking. It's extremely likely that this game will require a server side program to constantly run. I have little experience with these things and since it's a prototype i'd like the easiest options for achieving this.

I am looking to make this game for the web and mobile devices, although at present I only have access to ios hardware, (no android etc).

I just want to get the bare bones of this set up so I can test it from the earliest opportunity to see if it's fun.

EDIT - doesn't unity have some inbuilt networking stuff in it?


texts: Dealing with back to front drawing with alpha blending and z buffer for a list of 2d quads

texts:
I'm using depth buffer as a layering system for my 2d render and I have to draw them from back to front to make semi-transparent quads work out. The problem is I have to sort my quads vector based on their depths whenever I add or remove one and that is time consuming. I've done this before, but I'm not sure what's the down side because in my mind I think if I sort a vector of let's say 5000 quads, then it'll really keep CPU busy if I remove one of them and sort the other 4999 items in a single frame.

I need to know if there is an alternate way for this or this is just it.


texts:
Here is my code. I have an empty Gameobject directly underneath the child with a small radius checking the ground every thing seems to be correctly covered, but for some reason the jumping mechanic is very finicky and broken feeling. Can you take a look a tell me what you see? Thank you for your time!

public class PlayerMovement : MonoBehaviour
{

    public float speed;
    public float height;

    public Transform groundCheck;
    public float groundCheckRadius;
    public LayerMask whatIsGround;
    private bool grounded;

    private bool doubleJumped;

    // Update is called once per frame

    void FixedUpdate ()
    {
        if (grounded)
        {
            doubleJumped = false;
        }

        if (Input.GetButton ("Horizontal"))
        {
            transform.Translate (Vector3.right * speed * Time.deltaTime);
        }

        if( Input.GetButton("Left"))
        {
            transform.Translate (Vector3.left * speed * Time.deltaTime);
        }

        if (Input.GetButton ("Jump") && grounded)
        {
            //transform.Translate (Vector3.up * height * Time.deltaTime);
            Jump();
        }

        if (Input.GetButtonDown ("Jump") && !doubleJumped && !grounded)
        {
            Jump();
            doubleJumped = true;
        }

        grounded = Physics2D.OverlapCircle(groundCheck.position,groundCheckRadius,whatIsGround);

    }

    void Jump()
    {
        transform.Translate (Vector3.up * height * Time.deltaTime);
        return;
    }
}


texts: so im going through the roll a ball tutorial for unity and ive gotten though setting up all the controls to allow my ball character to move around the space ive built. but the tutorial says nothing about setting up what buttons trigger the movement. i found out where the input settings are for each axis and ive tried messing around in there but no matter what i do nothing seems to make my ball start moving around its little platform. does anyone know how to fix this issue?


texts: How to determine where on a path my object will be at a given point in time?

texts:
I have map and an obj that is meant to move from start to end in X amount of time.

The movements are all straight lines, as curves are beyond my ability at the moment. So I am trying to get the object to move from these points, but along the way there are way points which keep it on a given path.

The speed of the object is determined by how long it will take to get from start to end (based on X).

This is what i have so far:

//get_now() returns seconds since epoch
var timepassed = get_now() - myObj[id].start; //seconds since epoch for departure
var timeleft = myObj[id].end - get_now(); //seconds since epoch for arrival
var journey_time = 60; //this means 60 minutes total journey time
var array = [[650,250]]; //way points along the straight paths

if(step == 0 || step =< array.length){
  var destinationx = array[step][0];
  var destinationy = array[step][1];
}else if( step == array.length){
  var destinationx = 250;
  var destinationy = 100;
} else {
  var destinationx = myObj[id].startx;
  var destinationy = myObj[id].starty;
}
step++;

When the user logs in at any given time, the object needs to be drawn in the correct place of the path, almost as if its been travelling along the path whilst the user has not been at the PC with the available information i have above.

How do I do this?

Note: The camera angle in the game is a birds eye view so its a straight forward X:Y rather than isometric angles.


texts: Why i'm not getting the FPSController Rotation values?

texts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;

public class RotateObject : MonoBehaviour
{
    public UnityStandardAssets.ImageEffects.Blur blur;
    public UnityStandardAssets.ImageEffects.BlurOptimized blurOptimized;
    public FadeScript fadescript;
    [SerializeField] Quaternion targetRotation;    /// Rotation you want to achieve.
    [SerializeField] private float s;       /// Rotation duration.
    private Quaternion initialRotation;     /// Your GameObject's initial rotation.
    private float t;                        /// Your 't' reference.
    private FirstPersonController fpcscript;

    void Awake()
    {
        fpcscript.enabled = false;
        fpcscript = transform.GetComponent<FirstPersonController>();
        initialRotation = transform.localRotation;
    }

    void Update()
    {
        if (fadescript.alphaZero == true)
        {
            if (t < 1.0f)
            {
                transform.rotation = Quaternion.Lerp(initialRotation, targetRotation, t);
                t += (Time.deltaTime / s); /// Each 60 frames [optimally] t reaches 1, divided by your duration, it will reach 1 on 'x' seconds.
            }
            else /// Your rotation ends here:
            { /// reset 't' [if you please], and reset 'initialRotation'
                initialRotation = transform.rotation;

                blur.enabled = false;
                blurOptimized.enabled = false;
                fpcscript.enabled = true;
            }
        }
    }
}

The script is attached to FPSController.
In the Inspector the Rotation of the FPSController is: X = 7 Y = 112 Z = -31

But when i'm using a break point on the line in the Awake:

initialRotation = transform.localRotation;

I see that initialRotation values are: (-0.2, 0.8, -0.2, 0.5)

What i want to do is to rotate the transofrm from X = 7 Y = 112 Z = -31 to rotation 0,0,0
That is why i also didn't set any values to targetRotation since i want it to rotate to 0,0,0


texts: Does AddForce continue to add force indefinitely?

texts:
Does the AddForce method continue add velocity to an object forever? Does it need to be limited by another line of code?

Sorry if it is too broad or too simple; I am completely new to programming and Unity, as well as 3D development.


texts: How can I make a transparent hole with shaperenderer using stencil masking in libgdx?

texts:
I'm making a 2d game, where I need a resizeable, moveable rectangle outline. I'm trying to use stencil masking to do it by cutting a hole in a solid rectangle, and I thought this would help:

How can I add a transparent overlay to a UI in libGDX?

But all I get is a solid box. Here's my code:

        Gdx.gl.glClear(GL_STENCIL_BUFFER_BIT);
        Gdx.gl.glColorMask(false, false, false, false);
        Gdx.gl.glDepthMask(false);
        Gdx.gl.glEnable(GL20.GL_STENCIL_TEST);
        Gdx.gl.glStencilFunc(GL20.GL_ALWAYS, 0x1, 0xffffffff);
        Gdx.gl.glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);

        shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);

        shapeRenderer.box(cubby.xpos + 5 , cubby.ypos + 5, 0, cubby.size - 10, cubby.size - 10, 0);

        shapeRenderer.end();

        shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);

        Gdx.gl.glColorMask(true, true, true, true);
        Gdx.gl.glDepthMask(true);

        Gdx.gl.glStencilFunc(GL_NOTEQUAL, 0x1, 0xffffffff);
        Gdx.gl.glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

        shapeRenderer.box(cubby.xpos, cubby.ypos,0,cubby.size, cubby.size, 0);

        shapeRenderer.end();

        Gdx.gl.glDisable(GL20.GL_STENCIL_TEST);


texts: I can't clear the paint image in my Canvas

texts:
I'm trying to make the Mario move, but somehow it leaves traces behind, can anybody help???

var canvas = document.getElementById("screen");
var ctx = canvas.getContext("2d");
var mario;
var marioSprite;
var tiles;
var speedX = 1;

//marioSprite Specification
mario = {
    //target picture specification X & Y, Width & Height
    px:276,
    py: 44,
    pwidth: 16,
    pheight: 16,
    //drawing on Canvas specification X & Y, Width & Height
    cx: 16,
    cy: 116,
    cwidth:16,
    cheight:16,
}

//draw Mario in Canvas
function drawMarioSprite(){
    marioSprite = new Image();
    marioSprite.src = 'file:///C:/Users/MASTONO ALI/Desktop/img/characters.gif';
    marioSprite.addEventListener('load', e => {
    ctx.drawImage(marioSprite,
        mario.px, mario.py, mario.pwidth, mario.pheight,
        mario.cx, mario.cy, mario.cwidth, mario.cheight);
    });
    this.position = function() {
        this.mario.cx += speedX;
    }
    position();
}//drawMarioSprite() end

//drawTiles and tilesLoop
function drawTiles() {
    tiles = new Image();
    tiles.src = 'file:///C:/Users/MASTONO ALI/Desktop/img/tiles.png';
    tiles.addEventListener('load', e => {
        tilesLoop();
    });
}
function tilesLoop(){
    for (let x = 0; x < 25; x++){
        for (let y = 11; y < 13; y++){
            ctx.drawImage(tiles,
                0, 0, 26, 26,
                x*12, y*12, 20, 20);
        }
    }
}//drawTiles() end

function draw(){

    drawMarioSprite();
    drawTiles();
    window.requestAnimationFrame(draw);
}

window.requestAnimationFrame(draw);

thank you


texts: Fading back and fourth Unity Image alpha

texts:
I'm trying to create a way in which if I press a button, it'll highlight other objects whilst at the same time fading other objects. I also have other buttons that will fade and highlight different objects. Some of which may have been modified by the first button.

I had done this originally in a really dumb way like so

public void Highlight()
{
    foreach (Image image in imagesToHighlight)
    {
        Color c = image.color;
        if(c.a < maxColor)
        {
            c.a = maxColor;
        }

        image.color = c;
    }

    foreach (Image image in imagesToFade)
    {
        Color c = image.color;
        if(c.a > halfColor)
        {
            c.a = halfColor;
        }
        image.color = c;
    }
}

This works, but I was wanting it to happen gradually to provide a smother transition. I managed to get the fade working, by changing the code to this:

IEnumerator Fade(Image image)
{
    float elapsedTime = 0.0f;
    Color c = image.color;
    while (elapsedTime < 1)
    {
        yield return fadeInstruction;
        elapsedTime += Time.deltaTime;
        c.a = 1.0f - Mathf.Clamp01 (elapsedTime / fadeTime);
        image.color = c;
    }
}

I then call the method in my foreach loop like so:

foreach (Image image in imagesToFade)
{
    StartCoroutine (Fade (image));
}

Again, this works fine. The problem I'm having is checking to see if the image is faded, and if it is and needs to be highlighted, it reverses from the fade value to the highlight value (0.5 to 1.0).

I thought this would be a simple change as did this

IEnumerator HighLight(Image image)
{
    float elapsedTime = 0.0f;
    Color c = image.color;

    while (elapsedTime < 1 )
    {
        yield return fadeInstruction;
        elapsedTime += Time.deltaTime;

        c.a +=  Mathf.Clamp01 (elapsedTime / fadeTime);

        image.color = c;
    }
}

Simply changing the alpha line. However, now my image alphas jump all of the place in the highlight method. I'm at a loss as to how I can fix this. Can someone please tell me what I'm doing wrong?


texts: Array-based tilemaps and bounding box (aabb?), how to do efficient tile collisions?

texts:
At one point in my game I had every tile as it's own object, so that I could use standard AABB collision testing easily. I later realized this was horrible for performance and simply made my tiles be an array of numbers denoting which 16x16 segment to use.

However, this also means that I can no longer use standard AABB collision testing for tilemaps, since tiles don't have their own AABBs anymore. The first method I've tried is using hotspot collisions (per-pixel, see this page), but I'd really like to instead use some kind of bounding-box based collision testing instead of manually placing hotspots. The only methods I can think of are horrible for performance; using separate AABBs for tiles (already tried) and checking every singe pixel inside a bounding box / AABB for collision with a tile (likely even worse for performance).

What is a way that I can detect collisions using my character's bounding box while keeping my tiles simply an array of numbers, and not having a large performance impact?


texts: Libgdx How to overlay two images on Table

texts:
I'm trying to set the player image inside the circle of the bars. I've tried to use stack, to position it topLeft but it does not work.

    Stack stack = new Stack();

    healthbar = new Image(new Texture(Gdx.files.internal("data/ui/healthbar.png")));
    playerLook = new Image(player.getFrame());
    stack.add(healthbar);
    stack.add(playerLook);

    Table table = new Table();
    table.top();
    table.setFillParent(true);

    table.add(healthbar).expandX().pad(10).left();
    table.add(playerLook).expandX().pad(10).left();

    stack.add(table);
    stage.addActor(stack);


texts: Problem with camera deapth culling only option and objects in front of each other

texts:
I have a prefab with 2 cameras. the 1st is rendering the world, the 2nd one all the suff in front of the 1st person characters "face". Now i have a problem with a gun using a muzzleflash - both on the deapth only camera. The muzzleflash is on the very front tip of the gun and i assume because the 2nd face camera is set to "deapth only" it causes the muzzleflash to be off place. I came up with 3 ideas

1: changing the layer of the muzzleflash to world for some frames everytime a muzzleflash appears

2: having a 3rd camera rendering the muzzleflash only

3: adjusting the gun on the face camera, the muzzleflash on the world camera

I assume the 1st two options have a huge overload, i prefer the 3rd one. But is it a good way to do it? How should i proceed in this situation? Or how do others?

I also have animations so it can appear on 2 positions, normal and scoped.

Edit Here is an image i added Debug.Break() as it was instantiated, its totally correct aligned.


texts: integrating leaderboard from Newgrounds in flash game

texts:
I have made flash game and I want to show a leader board in that game.
I have uploaded my game to kongregate.com.

I have made a scoreboard there with the name of overLoadScore (overload is the name of my game).
i dragged an instance of API Loader component.

in my Main.as file I have the code.

var scoreBoard:ScoreBoard = new SoreBoard();
scoreBrowser.scoreBoardName = "overLoadScore";
scoreBrowser.loadScores();
scoreBoard.period = ScoreBoard.ALL_TIME;

i am getting the error
    call to a possibly undefined method ALL_TIME with reference to static type class ScoreBoard.

although i have provided correct API ID and encryption key.But in the output window i am getting the message.
[Newgrounds API] :: No API ID entered in the API Connector component.

and i have created the scoreBoard which i mentioned earlier but what is this

[Newgrounds API] :: No scoreboards created for this movie.


texts: Java 2D World: Convert from mouse screen co-ords to screen co-ordinates?

texts:
I have a 2D world background made up of a Grid of graphics, which I display on screen with a viewport (800x600) and it all works.

My question is I have the following code to

convert the mouse co-ordinates to world co-ordinates

then

World co-ordinates to grid co-ordinates

then

grid co-ordinates to screen co-ordinates.

//Add camerax to mouse screen co-ords to convert to world co-ords.
int cursorx_world=(int)camerax+(int)GameInput.mousex;
int cursorx_grid=(int)cursorx_world/blocksize;  // World Co-ords / gridsize give grid co-ords
int cursorx_screen=-(int)camerax+(cursorx_grid*blocksize);

So is there anyway I can convert straight from mouse screen co-ords to screen co-ordinates?


texts: Mobile 3D engine renders alpha as full-object transparency

texts:
I am running a iOS project using the isgl3d framework for showing pod files.

I have a stylish car with 0.5 alpha windows, that I wish to render on a camera background, seeking some augmented reality goodness.

The alpha on the windows looks okay, but when I add the object, I notice that it renders the entire object transparently, where the windows are. Including interior of the car.

Like so (in example, keyboard can be seen through the dashboard, seats and so on. should be solid)

The car interior is a seperate object with alpha 1.0.

I would rather not show a "ghost car" in my project, but I haven't found a way around this.

Have anyone encountered the same issue, and eventually reached a solution ?


texts: Is there a difference in these two ways of rendering sprites?

texts:
I use an OrthogonalTiledMapRenderer:

renderer = new OrthogonalTiledMapRenderer(world.getMap());

and I wonder if there is a differnce between this call:

renderer.getSpriteBatch().draw(sprite, sprite.getX(), sprite.getY());

and this:

sprite.draw(renderer.getSpriteBatch());

If there is a difference, what is it?


texts: Determine Resulting Angle of Wall Collision

texts: So I have an object moving in a direction towards a fixed horizontal or vertical wall. How do I compute the angle that the object should bounce off at? The object can approach the wall at an arbitrary angle.


texts: How to create a correct Unity package copy, which will not be replaced when you import?

texts:
I create a "Package 1" consisting of section A (unique) + section B (which will be repeated in all my other packages). This package works correctly is he is alone.

Next, I create a "Package 2" consisting of: section C (unique)  + Section B (from Package 1).

To save time, I replaced the texture maps in the materials belong to old section A parts and replace this part on section C (directly on models in the Mesh.)

I renamed most objects in the scene and in the package as a whole.

I delete all prefabs of «section A» and create prefabs «section C», because they are not pick up name changes. The prefabs of «section B», I left as is.

Now when I import «Package 2» in the scene that already contains the «Package 1», it begins the mess: «Package 1» Files are replaced by «Package 2», even them are named differently.

How to avoid it?

I can’t create each scene from scratch, unfortunately it will lead to the insane time-consuming.

Huge thanks for your support!


texts: Should I draw a button using a single shape (triangle list) and draw call, or multiple shapes and draw calls (triangle strip and line lists)?

texts: I know this is too simple for performance improvements to make much of a difference, but I find that knowing this information would be simple for many future scenarios. Basically, what I am trying to draw is a rectangle with text over it. I don't know whether it would be better to draw the entire thing using triangles, or use two draw calls (one using GL_TRIANGLE_STRIP for the rectangle, and the other using GL_LINES for the text). My worry is that the cost of the draw call outweighs the cost of reducing the number of vertices used.


texts: Create styled grid with phaserJS gaming framework

texts:
I am new to Phaser and this is my first game with Phaser gaming framework. Am trying to find the right way of coding a grid what you see in below image

In some articles is being suggested to code it with html and place it over the canvas but in that case am having issues when resizing the screen.

Any ideas how i can achieve such type of grids creation. I cant have it as a full image cause there are animations per each winning case and that current winning symbol is being highlighted with the points.

Thanks.


texts:
I've been working on circle to circle collision and have gotten the intersection method working correctly, but I'm having problems using the returned values to actually separate the circles from one another.

This is the method which calculates the depth of the circle collision

public static Vector2 GetIntersectionDepth(Circle a, Circle b)
{
    float xValue = a.Center.X - b.Center.X;
    float yValue = a.Center.Y - b.Center.Y;

    Vector2 depth = Vector2.Zero;

    float distance = Vector2.Distance(a.Center, b.Center);

    if (a.Radius + b.Radius > distance)
    {
        float result = (a.Radius + b.Radius) - distance;
        depth.X = (float)Math.Cos(result);
        depth.Y = (float)Math.Sin(result);
    }

    return depth;
}

This is where I'm trying to apply the values to actually seperate the circles.

Vector2 depth = Vector2.Zero;
for (int i = 0; i < circlePositions.Count; i++)
{
    for (int j = 0; j < circlePositions.Count; j++)
    {
        Circle bounds1 = new Circle(circlePositions[i], circle.Width / 2);
        Circle bounds2 = new Circle(circlePositions[j], circle.Width / 2);

        if(i != j)
            depth = CircleToCircleIntersection.GetIntersectionDepth(bounds1, bounds2);

        if (depth != Vector2.Zero)
        {
            circlePositions[i] = new Vector2(circlePositions[i].X + depth.X, circlePositions[i].Y + depth.Y);
        }
    }
}


texts: How to extract terrain heightmap from some free online map (OpenStreetMap,GoogleMaps, NASA WinWorld etc.)

texts:
I downloaded some small tile ( 10x10km ) from OpenStreetMap but I don't see what is the simplest way how to get actuall heightmap like this out of .osm file.

I'm looking to Python OSM API  but I don't see anything about height/altitude channel. Also OpenStreetMap wiki-page about relief and altitude is not very helpful.

In these two projects
pyvotons and
Shadow Mapper
they seem to do it somehow, but I hesitate to dig into
their code, if there is simpler answer.


texts: Estimate the time it takes for an object to travel from point A to point B

texts:
I have an object with vec2 position, velocity, and destination with 2 variables maxspeed and acceleration. In each step, its position is calculated as follows:

vec2 desiredVel = destination - position;

var dist = desiredVel.length;
if (2 * dist * acceleration < currentSpeed*currentSpeed)
    desiredVel.zero();

vec2 steering = desiredVel - velocity;
steering.setLength(acceleration);

velocity += steering * dt;
velocity.truncate(maxspeed);
currentSpeed = velocity.length();

position += velocity * dt;

Basically the object will accelerate to its maxspeed towards destination, then maintains  speed until the a certain distance to destination. At that distance, the object will decelerate at the -max acceleration rate so that it stops approximately to the destination point.

My question is that if I have an object with an initial velocity and I set a destination point, how can I estimate the time it will take to reach the destination point? Assuming its maxspeed and max acceleration doesn't change and no other force/acceleration applies to the object in the path.


texts: 3D 3-axes rotation into 3D 2-axes rotation

texts:
Hello everyone and thanks in advance to anyone who'll help me through this !

I am currently working on the Kinect V2 (for XBox One) to interact with an avatar.
I'd like to use the rotation quaternion that the SDK 2.0 give for each joint of the Skeleton. My avatar (virtual avatar of NAO robot) communicates through nautical angles, yaw, ptich and roll. There's no problem to convert quaternions into nautical angles, but here's my problem :

Let's take the shoulder as an example of joint; Where the Kinect express the rotation of my shoulder as a 3-axes rotation, I need to convert it into a 2-axes rotation.

So for my shoulder I have a [Yaw, Pitch, Roll] from the Kinect, which I want to convert into a [Pitch, Roll] for NAO's avatar

At the beginning, I didn't see the problem; I just ignored the Yaw angle. But I rapidly noticed that the movement was not the same than in the Kinect (and it makes sense).

Can someone help me ? How can I convert a 3D 3-axes rotation into a 3D 2-axes rotation ?


texts: Can anyone recommend a 3D model viewer with shading?

texts:
I am looking for a simple real-time OpenGL based render engine to show a 3D model on screen.

I prefer using 3DS Max's 'shader' materials (real-time materials) for editing.

Do you know any good simple API to include it in an OpenGL screen? Is there a simple tool to export from 3DS Max to that tool?


texts: How to synchronize the ball in a network pong game?

texts:
I’m developing a multiplayer network pong game, my first game ever. The current state is, I’ve running the physic engine with the same configurations on the server and the clients. The own paddle movement is predicted and get just confirmed by the authoritative server. Is a difference detected between them, I correct the position at the client by interpolation. The opponent paddle is also interpolated 200ms to 100ms in the past, because the server is broadcasting snapshots every 100ms to each client.

So far it works very well, but now I have to simulate the ball and have a problem to understanding the procedure.

I’ve read Valve’s (and many other) articles about fast-paced multiplayer several times and understood their approach. Maybe I can compare my ball with their bullets, but their advantage is, the bullets are not visible. When I have to display the ball, and see my paddle in the present, the opponent in the past and the server is somewhere between it, how can I synchronize the ball over all instances and ensure, that it got ever hit by the paddle even if the paddle is fast moving? Currently my ball’s position is simply set by a server update, so it can happen, that the ball bounces back, even if the paddle is some pixel away (because of a delayed server position).

Until now I’ve got no synced clock over all instances. I’m sending a client step index with each update to the server. If the server did his job, he sends the snapshot with the last step index of each client back to the clients. Now I’m looking for the stored position at the returned step index and compare them. Do I need a common clock to sync the ball?

EDIT:
I've tried to sync a common clock for the server and all clients with a timestamp. But I think it's better to use an own stepping instead of a timestamp (so I don't need to calculate with the ping and so on - and the timestamp will never be exact). The physics are running 60 times per second and now I use this for keeping them synchronized. Is that a good way?

When the ball gets calculated by each client, the angle after bouncing can differ because of the different position of the paddles (the opponent is 200ms in the past). When the server is sending his ball position, velocity and angle (because he knows the position of each paddle and is authoritative), the ball could be in a very different position because of the different angles after bouncing (because the clients receive the server data after 100ms). How is it possible to interpolate such a huge difference?

I posted this question some days ago at stackoverflow, but got no answer yet. Maybe this is the better place for this question.


texts:
Is there a way to export or publish some work to a folder so somebody else can open the .max file and does not have to reassign all the textures again?

My problem is that i used lots of textures straight from my texture folder in a completely different folder tree. So when i sent the file to someone else he needs to rebuild this tree exactly the same as i did or reassign every texture.

If there is no option like that do i have to change my workflow, in case others need to work with my files, and keep everything in the same folder? What is normal procedure to keep everything organized and compatible for each user?


texts: Orthographic Zooming with 0,0 at top/left

texts:
I'm trying to implement zooming on my 2D game. Since it's using orthographic projection, I thought it would be easy to implement zooming. After looking around the internet, I found a bunch of explanations and samples on how to do this if (0,0) is the center of the screen with the orthographic projection. The problem is, my ortho projection has (0,0) at the top-left (similar to XNA/Monogame, and a couple others). I could not find any examples about how to implement zooming to the center of the screen when the center is not (0,0).

And help/links/code examples would be greatly appreciated.


texts: Is there a free and open source 3D engine for Android?

texts:
Is there a free and unlimited open source 3D engine for Android? Something that is a direct, thin layer to the NDK?

I have only found two engines: Unity and Shiva 3D. But no free or open source ones.


texts: How to modify Game1.cs out of an object it contains?

texts: Assuming I Have a List<SomeClass> myList; in my Game1-class. It also contains an object of SomeOtherClass otherClass;. How would I modify myList (Add/Remove) out of the otherClass's logic? Or in other words how to get access to the Game1-instance in this situation?


texts: Cross-platform C++/OpenGL ES development (iOS/Android)

texts:
I already have reasonable experience with C++ and OpenGL, and I have recently decided to try out mobile game development. After successfully creating a simple OpenGL ES Android app using Java, I researched ways to target both Android and iOS with as little rewriting code as possible. I tried using Visual Studio 2015's proudly-boasted cross-platform app development tools, but found them to be too new and therefore extremely under-documented. I could build the template projects the program gave to me, but I couldn't figure out how, given these templates, I might add assets into the game or handle touch screen input.

I have an unfortunately specific desire, too specific to find with Google. I want to make an OpenGL ES game using C++, with thin platform-specific wrappers for Android and iOS. People have asked similar questions to me (though not exactly the same), and more than one person responding has stated that what I want to do is not only possible, but relatively easy, since I don't have to worry about UI.

I tried this tutorial, but it's almost three years old and therefore probably designed for older technology, and as a result I ran into various unaccounted-for bugs. As of right now, though, that tutorial is the closest thing to what I want that I've found. Everything else is either Android-only, or recommending that I pay hundreds of dollars a year to use the Marmalade SDK. At times I feel like just writing the code twice, once in Java and once in Objective-C, but I am kept motivated by the knowledge that this solution is possible, but for some reason, not covered anywhere in any modern detail.

To summarise, I want to make an OpenGL ES game for iOS and Android, with a single C++ codebase wrapped in small amounts of platform-specific code. However, despite the fact that several people have recommended this approach, no one can tell me how to do it. Can somebody tell me if it's actually possible, and if so, what I can do or where I can go to learn how?


texts:
Im creating octree manually and want function for effectively divide all nodes and their subnodes - For example - I press button and subnodes divided - press again - all subnodes divided again.
Must be like - 1 - 8 - 64. The problem is - i dont understand how organize recursive loops for that.

OctreeNode in my unoptimized implementation contain pointers to subnodes(childs),parent,extra vector(contains dublicates of child),generation info and lots of information for drawing.

class gOctreeNode
            {
   //necessary fields
    gOctreeNode* FrontBottomLeftNode;
    gOctreeNode* FrontBottomRightNode;
    gOctreeNode* FrontTopLeftNode;
    gOctreeNode* FrontTopRightNode;
    gOctreeNode* BackBottomLeftNode;
    gOctreeNode* BackBottomRightNode;
    gOctreeNode* BackTopLeftNode;
    gOctreeNode* BackTopRightNode;
    gOctreeNode* mParentNode;
    std::vector<gOctreeNode*> m_ChildsVector;
    UINT mGeneration;
    bool mSplitted;
    bool isSplitted(){return m_Splitted;}

    .... //unnecessary fields
    };

DivideNode of Octree class fill these fields, set mSplitted to true, and prepare for correctly drawing. Octree contains basic nodes(m_nodes). Basic node can be divided, but now I want recursivly divide already divided basic node with 8 subnodes. So I write this function.

    void DivideAllChildCells(int ix,int ih,int id)
    {
        std::vector<gOctreeNode*> nlist;
        std::vector<gOctreeNode*> dlist;

        int index = (ix * m_Height * m_Depth) + (ih * m_Depth) + (id * 1);//get index of specified node
        gOctreeNode* baseNode = m_nodes[index].get();

        nlist.push_back(baseNode->FrontTopLeftNode);
        nlist.push_back(baseNode->FrontTopRightNode);
        nlist.push_back(baseNode->FrontBottomLeftNode);
        nlist.push_back(baseNode->FrontBottomRightNode);
        nlist.push_back(baseNode->BackBottomLeftNode);
        nlist.push_back(baseNode->BackBottomRightNode);
        nlist.push_back(baseNode->BackTopLeftNode);
        nlist.push_back(baseNode->BackTopRightNode);

        bool cont = true;
        UINT d = 0;//additional recursive loop param (?)
        UINT g = 0;//additional recursive loop param (?)

        LoopNodes(d,g,nlist,dlist);

        //Divide resulting nodes
        for(UINT i = 0; i < dlist.size(); i++)
        {
            DivideNode(dlist[i]);
        }
    }

And now, back to the main question,I present LoopNodes, which must do all work for giving dlist nodes for splitting.

    void LoopNodes(UINT& od,UINT& og,std::vector<gOctreeNode*>& nlist,std::vector<gOctreeNode*>& dnodes)
    {
        //od++;//recursion depth
        bool f = false;

        //pass through childs
        for(UINT i = 0; i < 8; i++)
        {
            if(nlist[i]->isSplitted())//if node splitted and have childs
            {
                //pass forward through tree
                for(UINT j = 0; j < 8; j++)
                {
                    nlist[j] = nlist[j]->m_ChildsVector[j];//set pointers to these childs
                }
                LoopNodes(od,og,nlist,dnodes);
            }
            else //if no childs
            {
                //add to split vector
                dnodes.push_back(nlist[i]);
            }
        }
    }

This version of loop nodes works correctly for 2(or 1?) generations after - this will not divide neightbours nodes, only some corners. I need correct algorithm.
Screenshot

All I need - is correct version of LoopNodes, which can add all nodes for DivideNode.


texts: I am designing a simple game and am looking for some help designing different level/ranks. For instance, starting from "Novice" to "Intermediate" to "Master". Is there are repository somewhere that records these from various games? For instance, from World of Warcraft, Diablo etc. Any suggestions?


texts: Is there any point in including manuals with games today?  It seems like most manuals are more for background story or art than any actual help.  Additionally, it seems like most games are including "help" inside of their games in the means of tutorials or similar means.  Do enough users actually look at their manuals to make them worthwhile to include?


texts:
I've been using Blender for two days now, and ran into an issue while following a tutorial.

Before anything else, I'd like to show you all what my problem precisely is. Here is a short video I uploaded: click here. I thought it may be easier for you all to help me identify and solve my problem more accurately with a visual aid.

I would like to emphasize that this issue began to occur after I extruded that trapezoidal region (misstated as a parallelogram in the video). I decided that I did not want the extruded region, and just hit undo. Ever since then, I began to experience the problem you viewed.

Thanks.


texts:
While running Dijkstra's Algorithm to assign a direction to every tile and when an object land on the tile, follow the direction to a goal. I encountered an infinite loop (or I think it is). The following is my code:

while (openList.Count > 0)
    {
        Debug.Log("Running alg");
        failsafe++;
        if (failsafe > 1000) { break; }

        Tile currentTile = openList[0];
        openList.Remove(currentTile);
        closedList.Add(currentTile);

        List<Tile> neighbours = GetNeighbours(currentTile.localX, currentTile.localY, grid);

        foreach (var neighbour in neighbours)
        {
            if (!closedList.Contains(neighbour))
            {
                neighbour.parentX = currentTile.localX;
                neighbour.parentY = currentTile.localY;
                openList.Add(neighbour);
            }
        }
    }

Under these conditions, the failsafe triggered and broke the loop. The grid is a 11x11 grid and as such by my understanding should have never reached 1000 cycles.

When the failsafe triggers, it explored 9 tiles away from the goal and the rest are unexplored.

What am I doing wrong here?


texts: PID controller error value for heading correction

texts:
I'm using a PID controller in my AI to steer my NPCs to a desired heading (by adding torque). I've adapted the code from here: http://answers.unity3d.com/questions/199055/addtorque-to-rotate-rigidbody-to-look-at-a-point.html

The above example uses the cross-product of the two headings as the error value for the PID controller. This works great if the angle between the desired and current headings is less than 90 degrees but if the angle is greater than that, the PID controller corrects to the opposite direction than I want (as it tries to correct to zero)!

What is a good error value between two vectors to pass into a PID controller that works no matter what the angle between the desired, and current heading?

Note: because the PID controller returns the correction as a vec3, the error value must also be a vec3


texts: What is the most efficient method of creating a detailed 3d tileset in a 3d game that uses a grid?

texts:
Well, the most efficient method might be with how minecraft does the terrain by using a single block for a single grid, but one thing I am concerned about is that the method minecraft uses is poorly mixed near the edges where 2 different blocks meet. I would like the blocks to mix together nicely, similiar to how modern 2d games does their tiles.

I had some thoughts.

Perhaps one could adjust the alpha of the texture so that it blends well near the end? So at the edge, between 2 different blocks type, both of the blocks would exit where 1 of the block would be alpha-blended together with the other block based on the priority value of the block.

That's the idea I have currently but I have some doubts about it.

If there's any inquiry about my question feel free to ask.

Edit: Well, even though I use minecraft as an example, it's not a sandbox game, it's just I would like to use a grid style of terrain that some 2D game uses even when it's not sandbox (e.g. Mark of the Ninja) but in a 3D environment instead. An efficient method of doing that is concerned.


texts: How to calculate the dot product between the input direction and a character with root motion?

texts:
I need to calculate the dot product between my character movement direction and the input being pressed by the player. When the character movement was being controlled only by code, I was using something like this:
movementInputVector = new Vector3(inputDirection.y, 0, inputDirection.x) * Time.fixedDeltaTime;
rigidbody.MovePosition(transform.position + movementInputVector);

With this movement code, it was possible to calculate the dot product using the character's tansform.forward and the movement input vector.
It happens that I discovered that my movement needs to use root motion and after this change, I can't find a way to generate a consistent dot product anymore. Already did some attempts, but none of them worked.
Firstly, I tried to use the transform.forward, as it did worked before:
MovementDirectionDot = Vector3.Dot(transform.forward, movementInputVector);

But the result was 0, no matter the direction I pressed as input.
Then I tried to use the root bone of the character as reference:
MovementDirectionDot = Vector3.Dot(rootBoneTransform.forward, movementVector);

This attempt generated inconsistent values from ~-0,07 to ~9.
Taking a look at the transform.forward values, I've noticed it doesn't change as the character moves, remaining as a vector3(0,0,1) the whole time. Also, I tried to normalize all vectors involved and the same results happened.
So I have no clue what to do now, I don't know what vector should be used in this method in order to get back the correct dot product ranging from -1 to 1. Does anyone have an insight on this?