# Question
Title: River to nowhere - how do I make a pathfinder move to a destination that doesn't exist yet?
Let me start with the basics. Here's what I have:

* A height map built on a few different combinations of noise functions
* Rivers that are generated after the height map and flow from pseudorandom points to water following an A\* algorithm

What I'm trying to do:

* Create a "zoomed in" portion of this map without generating the whole map

Why?

* The map is very large, and storing all the points in the height map in its zoomed-out form already takes 100+ Mb.
* I decided the best way to store maps is just store the seeds used to generate them, which takes a couple of kilobytes.
* This allows me to generate identical maps every time
* However, when it comes to rendering such a map, the size does matter, since a bigger map means a bigger array/map/list holding it and a bigger chunk of memory dedicated to it.
* So instead of rendering the whole map at once, I want to be able to render small, manageable sections and stitch them together into a full map with a higher resolution.

I figure that I can just sample the noise function more frequently, and this will fill in points in between points to increase resolution. This works. The problem is when I get to edge cases.

In the full map, I make the edge believe that everything beyond it is a copy of the edge tile in question.

When I get to the smaller section of the map, I'm not quite sure how to deal with the edge case, especially when it comes to rivers:

**Say a river in the large map starts outside of the smaller section, but flows through the smaller section. How do I make sure that river is created?**

**Or say a river starts in my small section but ends at an ocean that isn't located in that section - an ocean that isn't generated at all but theoretically exists as a result of the noise function at those coordinates. Now what do I do?**

I have an idea of a possible solution, but I don't know how to execute it. I generate sets of river tiles in my world generation code, and I *could* just generate a full map at low resolution and copy the river tiles to the smaller map. However, this would leave gaps in the river, realistically in every other tile if I zoomed in to 2x scale. Is there some way I can fill in surrounding tiles to ensure that my river won't change scale?

If you would like code or pictures, please comment and I'll post them. I'm just not sure what I need to include that would actually be helpful and not just clutter.

Edit: I'm adding some pictures that might help explain the situation, everyone likes pictures right? The first one is an "unzoomed" map. The second one has twice the resolution of the first - the equivalent of zooming in on the map but still generating the whole thing. You can see that some of the rivers are now flowing in different directions (I made sure they start in the same place) because the terrain is now more detailed and they have found better paths. I'm not *as* concerned about that as I am about the questions in bold above. I don't need multiple maps at different resolutions, I just need one big map at high resolution.

# Answer
**Rivers need to be generated as a result of the procedural generation, not pathfinding.**

If you're going to use the map that way (not generating the whole thing, while viewing zoomed in portions), you can't generate your rivers with pathfinding. Essentially, **the rivers should be fractal**. Just like your terrain, you can zoom in to rivers for additional detail, but the larger structures of the fractal remain static.

However, this can't simply be another layer of noise, it needs to be closely tied to your existing terrain. Without knowing more about how you're generating the terrain it's hard to give specifics. But, you can use elevation data, moisture levels and multiple other layers to determine if a river should exist.

You may be able to combine strategies to ensure your rivers always reach oceans or lakes. Use pathfinding for your high level map. Then, when generating high resolution maps, utilize the pathfinding data from the lower resolution maps. This is essentially **fractal pathfinding**. When pathfinding for higher resolution, all you need to do is pathfind between each of the points found in the higher resolution.
> 1 votes

---
Tags: java, procedural-generation, maps
---


# Question
Title: Moving left and right not working as expected
I've been trying to get this working for about 2 hours now and as far as I'm concerned, it is working entirely, other than one thing.

The problem is that when my player is in the air, and they move right and collide with a wall, they simply collide. Simple. But when the player is moving left, and more commonly left and down or left straight after falling off a ledge and hitting a wall, they will almost always become grounded.

What is confusing me is that the left and right move scripts are exactly the same, with a few variables changed so that they are designed to go in opposite directions. My grounded check is also centered, so I don't imagine it could be happening to the left direction due to it being offset.

If anyone could help I would greatly appreciate it! Here is the script:

```
using UnityEngine;
using System.Collections;

public class Move : MonoBehaviour
{

    public RaycastHit2D groundhit;

    public float groundeddistance;
    public bool grounded;
    public float fallspeed;

    public RaycastHit2D uphit;
    public bool upblocked;
    public float upspeed;
    public float jumpcount;

    public float fallspeedpubset;

    public bool leftblock;
    public bool rightblock;
    public float sidespeed;
    public RaycastHit2D lefthit;
    public RaycastHit2D righthit;
    public float leftreach;
    public float rightreach;

    public bool jumping;

    public bool gravity;
    public float groundedwidth;
    public float upreach;
    public float jumpcountmax;
    public float repeatratejump;

    public bool cantground;

    public float leftclimbcount;
    public float rightclimbcount;
    public float leftclimbcountstoper;
    public float rightclimbcountstoper;

    // Update is called once per frame
    void Update()
    {

        fallspeed = fallspeedpubset;

        if (cantground == false)
        {
            groundhit = Physics2D.BoxCast(transform.position, new Vector2(transform.localScale.x - groundedwidth, transform.localScale.y), transform.eulerAngles.z, Vector2.down, groundeddistance);
            if (Physics2D.BoxCast(transform.position, new Vector2(transform.localScale.x - groundedwidth, transform.localScale.y), transform.eulerAngles.z, Vector2.down, groundeddistance) && groundhit.transform.tag == "Terrain")
            {
                grounded = true;
            }
            else { grounded = false; }

        }

        if (grounded == false && gravity) { transform.position = new Vector2(transform.position.x, transform.position.y - fallspeed); } else { }

        lefthit = Physics2D.BoxCast(new Vector2(transform.position.x - transform.localScale.x / 2, transform.position.y), new Vector2(0.01f, transform.localScale.y - 0.04f), transform.eulerAngles.z, Vector2.left, leftreach);
        if (Physics2D.BoxCast(new Vector2(transform.position.x - transform.localScale.x / 2, transform.position.y), new Vector2(0.01f, transform.localScale.y - 0.04f), transform.eulerAngles.z, Vector2.left, leftreach) && lefthit.transform.tag == "Terrain")
        {
            leftblock = true;
        }
        else { leftblock = false; }

        righthit = Physics2D.BoxCast(new Vector2(transform.position.x + transform.localScale.x / 2, transform.position.y), new Vector2(0.01f, transform.localScale.y - 0.04f), transform.eulerAngles.z, Vector2.right, rightreach);
        if (Physics2D.BoxCast(new Vector2(transform.position.x + transform.localScale.x / 2, transform.position.y), new Vector2(0.01f, transform.localScale.y - 0.04f), transform.eulerAngles.z, Vector2.right, rightreach) && righthit.transform.tag == "Terrain")
        {
            rightblock = true;
        }
        else { rightblock = false; }

        uphit = Physics2D.BoxCast(new Vector2(transform.position.x, (transform.position.y + transform.localScale.y / 2) + 0.01f), new Vector2(transform.localScale.x - groundedwidth, 0.01f), transform.eulerAngles.z, Vector2.up, upreach);
        if (Physics2D.BoxCast(new Vector2(transform.position.x, (transform.position.y + transform.localScale.y / 2) + 0.01f), new Vector2(transform.localScale.x - groundedwidth, 0.01f), transform.eulerAngles.z, Vector2.up, upreach) && uphit.transform.tag == "Terrain")
        {
            upblocked = true;
        }
        else { upblocked = false; }

        if (Input.GetKey("d") && rightblock == false)
        {
            transform.position = new Vector2(transform.position.x - sidespeed, transform.position.y);
        }
        else if (Input.GetKey("a") && leftblock == false)
        {
            transform.position = new Vector2(transform.position.x + sidespeed, transform.position.y);
        }

        //if(grounded && Input.GetButtonDown("Jump")) { grounded = false; cantground = true; jumping = true;  }
        if (grounded && Input.GetKeyDown("w") && upblocked == false) { InvokeRepeating("Jump", 0, repeatratejump); }
        if (grounded) { rightclimbcount = 0; leftclimbcount = 0; }
        //if (grounded == false && lefthit && Input.GetKey("a") && leftclimbcount <= leftclimbcountstoper && Input.GetKey("w") == false) { gravity = false; leftclimbcount = leftclimbcount + 1; upblocked = true;  } else if(jumping == false) { gravity = true; }
        //if (grounded == false && righthit && Input.GetKey("d") && rightclimbcount <= rightclimbcountstoper && Input.GetKey("w") == false) { gravity = false; rightclimbcount = rightclimbcount + 1; upblocked = true; } else if (jumping == false) { gravity = true; }

    }
    void Jump()
    {
        jumping = true;
        gravity = false;
        fallspeed = 0;
        if (upblocked == false)
            transform.position = new Vector2(transform.position.x, transform.position.y + upspeed);
        jumpcount += 1;
        if (jumpcount >= jumpcountmax) { CancelInvoke(); gravity = true; jumpcount = 0; jumping = false; }

    }
}

```

# Answer
## Your not working out the `origin` in `Physics2D.BoxCast()` correctly.

Using Unity, it is important to remember that traditional 2D refers to the *bottom-left corner* as its position or origin, while traditional 3D and `Physics2D.Boxcast` refers to the *dead-centre* as its position or origin.

*It is hard to tell whether you are specifically working in 2D, or working in 3D set up like 2D, because your origin logic seems to account for 2D along the x-axis, and 3D along the y-axis.* I will be assuming that you need to account for having a 2D-based origin; If your object is based in 3D, and its `transform.position` points to its dead-centre, you should not have to apply an offset *at all*.

From what I can find, online, `Physics2D.BoxCast` is not known to be user-friendly, especially for beginners. While the Unity API page is not very informative, I found this tutorial on YouTube that gives you a good idea of how it works.

Let's take a look at a broken up version of your code, to more accurately convey the logical issue:

---

## Movement Logic

Firstly, you are calling the function `Physics2D.BoxCast(Vector2 origin, Vector2 size, float angle, Vector2 direction, float distance)` to check for collision. I will be focusing on the first `Vector2` you send in, the *origin*, as this is where the logical error lies. Remember, the `Vector2 origin` determines the ***centre*** of the collider box.

### Moving Right

```
float x = transform.position.x + (transform.localScale.x / 2);
float y = transform.position.y;
Vector2 origin = new Vector2(x, y);

```

So you correctly move into the center of your object along the x-axis, but fail to adjust at all for the y-axis. This gives you a collision box like this:

The problem is, the origin of your player should always be the same. It is hard to know exactly how you have it set up, and different users have their preferences in accounting for origin and offsets, but traditionally it would look something like this:

As you can see, the box covers the bottom half of the player, and reaches *that same distance* underneath the player. This will result in collisions with the ground if the player is still within a distance of *half height*, even if the player is not actually touching the ground. In turn, *even though this logic appears to work*, you will be triggering `grounded` far earlier than you probably intend to.

### Moving Left

```
float x = transform.position.x - (transform.localScale.x / 2);
float y = transform.position.y;
Vector2 origin = new Vector2(x, y);

```

In this case, we still have the same logical problem along the y-axis. However, since you have *deducted* the offset from your `x` value, you also move the center further out to the left. This gives you something like this:

As you can see, by moving the x offset in the *opposite* direction, your collider box does not cover the player *at all*. This means that moving left will not only result in some fairly premature collisions, but during this movement there is no collision check on the player, at all!

### The solution

The solution is quite simple. Correctly using offsets, we can determine the correct origins to use. To correctly centre the collider around the player, we use an origin value of `new Vector2((transform.position.x + transform.scale.x/2), (transform.position.y + transform.scale.y/2))`.

I *think* you might be intending to deliberately check the area above, below, to the right and to the left of the player. I'm not quite sure *why* you would be opting to check collision in this way, and to elaborate and further delve into your code I would have to go into far more discussion than is suitable for this forum, but these are the origins you would use for calling the `Physics2D.BoxCast()` on the spaces *around* the player:

```
Vector2 leftOrigin = new Vector2(transform.position.x - (transform.scale.x/2)),
                                (transform.position.y + (transform.scale.y/2));

Vector2 rightOrigin = new Vector2(transform.position.x + (transform.scale.x * 1.5),
                                 (transform.position.y + (transform.scale.y/2));

Vector2 upOrigin = new Vector2(transform.position.x + (transform.scale.x/2)),
                              (transform.position.y + (transform.scale.y * 1.5));

Vector2 downOrigin = new Vector2(transform.position.x + (transform.scale.x/2)),
                                (transform.position.y - (transform.scale.y/2));

```

As a final note, you will notice that `rightOrigin` and `leftOrigin` use `*1.5` instead of `/2`. That is because we have to move over the player by an entire scale `*1` to be on the other side, and `/2` is the same as saying `*0.5`. I feel this is worth mentioning for the point of clarity, though it should be common sense.
> 0 votes

---
Tags: unity, 2d, movement, raycasting
---


title: Lag in collision detection

text:
# Question
Title: Lag in collision detection
I am a beginner with PyGame and am currently making a simple game using but I am having difficulty with the collision detection. When the game runs, the response to the collision detection (printing the score and removing the sprite) is very slow. The two responses occur at the same time but much later than when the sprites actually collide. I was wondering how I could change my code to fix this?

My code is here: http://pastebin.com/9t2hcAxH and I think the issue is in the game loop at the bottom.

# Answer
I can't try your code because I don't have the images, but I do see some problems:

When you spawn your sprites, for example:

```
elif event.type == ADDMET:
    asteroid = Meteor(720, random.randint(50, 300))
    asters.add(asteroid)
    astss = True

```

This creates an asteroid and adds it to the sprite group "asters". This is fine, but each time the event triggers, you spawn another asteroid and assign it to the variable "asteroid". This is going to cause a problem later:

```
if pygame.sprite.spritecollide(cat, asters, True):
        asters.remove(asteroid)
        life -= 1
        print(str(life))
        if life == 0:
            running = False
            break

```

The spritecollide function checks "cat" vs. the sprite group "asters". Any asteroids that collide with cat are removed from the group (because of the 'True' flag). spritecollide returns a list of these asteroids.

However, you're not using that list, you're just saying to remove "asteroid" from the group - but that may not be the asteroid that collided with cat! "asteroid" is going to be equal to the last asteroid you spawned. This problem is occurring with all your collision checks.

What you want to do is something like this:

```
hits = pygame.sprite.spritecollide(cat, asters, True)
for hit in hits:
        # don't need this, the "True" takes care of it
        # asters.remove(asteroid)
        life -= 1
        print(str(life))
        if life == 0:
            running = False
            break

```
> 1 votes

---
Tags: collision-detection, sprites, pygame, lag
---


# Question
Title: My character is hanging in the air after adding a capsule collider
I am using Unity 5.3. I have added a capsule collider to one of my models. I have added a rigidbody to my character. After rotating and translating my model. the model hangs in the air as shown in images below.

I think it is due to the capsule collider. Does capsule collider not adjust automatically after changing parts of the model, like when animating the model, or is it a fixed collider which does not change after animating the model?

How do I fix this problem?

# Answer
The `CapsuleCollider` does not automatically conform to animation. It will conform to the local or inherited transform, but will not change to fit the goalkeeper extending its arms upwards instead of outwards. While there is generally transform manipulation behind the animation, it is performed on the *child* objects, which does not effect the *parent*. We can see this in screenshot two, where the collider has not shrunk to fit the goalkeeper, but has rotated in response to the transform rotation.

I can see two possible solutions; Manually altering the collider via code seems to be the easiest, but the goalkeeper will still appear to float, to some degree. Alternatively, you can place smaller colliders on the individual bones of the goalkeeper, where the animation should directly effect the transform values.

### Altering the `CapsuleCollider` via code

If you manually alter the dimensions of the `CapsuleCollider` when the goalkeeper changes its state, you should be able to at least create a tighter fit. For instance, when the goalkeeper throws its arms up, you could directly lower the `CapsuleCollider.radius` to constrict the collider to the tighter model.

```
CapsuleCollider collider = GetComponent<CapsuleCollider>();
collider.radius = 3.5;

```

It is still going to look like your goalkeeper is floating, to some degree. At the end of the day, you are still using a single 3D primitive to determine the collision of a more intricate 3D model. The difference is that your goalkeeper will slide on the straight space between the leg and the arm, as opposed to the open space left behind by the outstretched arms.

### Using multiple colliders

If you instead attach smaller colliders to the bones in your animation, you can get away with more precise collision detection, at the cost of processing power. You might want to consider using more than just the `CapsuleCollider`, in this case. For example, the `SphereCollider` would be a better fit for the head, and a `BoxCollider` might be a more efficient way to manage the torso.

Simple apply a collider to each bone where animation is performed, and ensure that the collider appropriately covers the part of the mesh animated through that bone. For example, the shoulder bone would contain a collider for the upper-arm, while the elbow would contain the collider for the forearm and hand, assuming there were no more bones to animate hand movement.
> 1 votes

---
Tags: physics, unity
---


title: Game developing on the oculus rift

text:
# Question
Title: Game developing on the oculus rift
My question is, do I need the oculus rift development kit to develop games or can I do it with a standard pair of oculus rift,and if I can do it with a standard pair of oculus rift why does the development kit exist?

# Answer
> 2 votes
The Dev Kit existed to get the Oculus product in the hands of developers before the actual consumer product existed.

This was partially to combat the chicken-egg problem (no games mean no consumer interest, no consumers mean no developer interest).

Another reason was to get developers accustomed to the concept of VR as it has different challenges from a user/gameplay perspective.

The third reason is to create hype and press interest as VR is a relative new tech (if you ignore the 90s experiments).

The reason dev kits for consoles or other tech exists is usually because those have features required for development such as extra video connectors to monitor system internals, means to attach debuggers to processes running on the hardware or simoly a opened operating system to be able to deploy software easily.

The Oculus does not 'run' the software but can be regarded as an extra screen and some input controllers- thus you can develop fine with the regular consumer kit.

The tools may require licenses to get access to the SDK (Software Development Kit) that holds libraries and code samples to actually do the development. Though some (I think UE4- not sure)may come with the required libraries.

---
Tags: oculus
---


title: Json format to request to Java Server

text:
# Question
Title: Json format to request to Java Server
I have this class in java, I'm using Jersey.

```
 @Path("/bandas")
 public class BandaResource {

static private Map<Integer, Banda> bandasMap=someSource();

@GET
@Produces({ "application/json" })
public List<Banda> getBandas()
 {
    return new ArrayList<Banda>(bandasMap.values());
 }

@POST
@Consumes("text/xml")
@Produces("text/plain")
          public String adicionaBanda(Banda banda) {
           banda.setId(bandasMap.size() + 1);
           bandasMap.put(banda.getId(), banda);
           return banda.getNome() + " adicionado.";
    }
}

```

In Unity when I request all the information I get an answer from server:

```
 URL url = new URL ( "http://localhost:8080/restful-exemplo/rest/bandas" );
 WWW www = new WWW(url);

```

Debug.Log (www.data) returns:

*{"banda":\[{"anoDeFormacao":"1968","id":"1","nome":"Led Zeppelin"},{"anoDeFormacao":"1973","id":"2","nome":"AC/DC"}\]}*

But I want to send, I don't have any idea how but I tried:

```
 string JSON=" {\"nome\":\"Teste\", \"anoDeFormacao\":\"1988\",\"id\":\"4\"}";

    Hashtable postHeader = new Hashtable();
    postHeader.Add("Content-Type", "text/json");

    UTF8Encoding encoding = new System.Text.UTF8Encoding();
    WWW request = new WWW(url, encoding.GetBytes(JSON.ToCharArray()), HashtableToDictionary<string, string>(postHeader));

```

Well, it returns a error (WWW Error: 415 Unsupported Media Type ), is the idea correct?

# Answer
> 1 votes
Your Java method is declared with `@Consumes("text/xml")`. That means it expects the MIME-type `text/xml` and XML-encoded data.

But on the Unity-side you are using a header to set the content-type to `text/json` and send JSON-encoded data. The result is a `451 Unsupported Media Type` HTTP error, just like the documentation says.

Make sure the Unity-side sets the content-type header to the same MIME-type the server method consumes. When you want to use JSON, then that would be `application/json` (`text/json` is incorrect, but might still work). If you would like to use `text/xml` instead, you also need to format your data as XML on the Unity-side.

---
Tags: unity, java, json
---


title: Camera follow behind a Model

text:
# Question
Title: Camera follow behind a Model
I am trying to learn about the Camera in a 3D space and wanted to 3rd person type of camera. Right now, I directly control my camera and it doesn't follow anything. It works like a first-person camera. I load my Model in my `Game1.cs` and draw it like this:

```
Model player;

protected override void LoadContent()
{
    // This is the default cube from Blender (when you first open up the program)
    player = this.Content.Load<Model>("Cube");
}

protected override void Draw(GameTime gameTime)
{
    foreach (ModelMesh mesh in player.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.View = camera.View;
            effect.World = Matrix.CreateTranslation(5f, 1, 10f);
            effect.Projection = camera.Projection;

            mesh.Draw();
        }
    }

    base.Draw(gameTime);
}

```

I want my camera to behind the cube or `player` and follow it. I think I have to change `PreviewMove` method in my `Camera` class but I don't know what needs to be changed. My guess is that I have to make a world matrix for the camera and set it behind the cube and update it whenever I move the cube. From there I would move the movement (W,S,A,D) code to the player movement.

But like I said, I don't know how I would implement this. If someone can provide any help or link me to a tutorial, it would be greatly appreciated. Thanks for your time!

Camera Class:

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Model3D
{
    class Camera
    {
        // Attributes
        private Vector3 camLookAt;
        private Vector3 camPosition;
        private Vector3 camRotation;
        private float cameraSpeed;
        private float mouseSensitivity;
        private Vector3 mouseRotationBuffer;
        private MouseState currentMouseState;
        private MouseState previousMouseState;
        private GraphicsDevice device;

        // Properties
        public Matrix Projection
        {
            get;
            protected set;
        }

        public Matrix View
        {
            get { return Matrix.CreateLookAt(camPosition, camLookAt, Vector3.Up); }
        }

        public Vector3 Position
        {
            get { return camPosition; }
            set
            {
                camPosition = value;
                UpdateLookAt();
            }
        }

        public Vector3 Rotation
        {
            get { return camRotation; }
            set
            {
                camRotation = value;
                UpdateLookAt();
            }
        }

        // Constructor
        public Camera(GraphicsDevice device, Vector3 position, Vector3 rotation, float fieldOfView = 45f, float speed = 10f, float sensitivity = 10f)
        {
            // Set the GraphicsDevice
            this.device = device;

            // Set camera speed & mouse sensitivity
            cameraSpeed = speed;
            mouseSensitivity = sensitivity;

            // Setup projection matrix
            Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(fieldOfView), device.DisplayMode.AspectRatio, 0.5f, 1000f);

            // Set camera position and rotation
            MoveTo(position, rotation);
        }

        // Set camera's position & rotation
        private void MoveTo(Vector3 pos, Vector3 rot)
        {
            Position = pos;
            Rotation = rot;
        }

        // Update LookAt Vector
        private void UpdateLookAt()
        {
            // Build a rotation matrix
            Matrix rotationMatrix = Matrix.CreateRotationX(camRotation.X) * Matrix.CreateRotationY(camRotation.Y);

            // Build LookAt offset
            Vector3 lookAtOffset = Vector3.Transform(Vector3.UnitZ, rotationMatrix);

            // Update camera's LookAt vector
            camLookAt = camPosition + lookAtOffset;
        }

        // Simulate movement
        private Vector3 PreviewMove(Vector3 amount)
        {
            // Create a rotate matrix
            Matrix rotate = Matrix.CreateRotationY(camRotation.Y);

            // Create movement vector
            Vector3 movement = new Vector3(amount.X, amount.Y, amount.Z);
            movement = Vector3.Transform(movement, rotate);

            // Return value of camera position + movement vector
            return camPosition + movement;
        }

        // Method that actually moves the camera
        private void MoveCamera(Vector3 scale)
        {
            MoveTo(PreviewMove(scale), Rotation);
        }

        // Keyboard and Mouse movement
        public void Update(GameTime gameTime)
        {
            // For smoothing (might not be beneficial for FPS)
            float deltaTime = (float) gameTime.ElapsedGameTime.TotalSeconds;

            // Mouse attributes
            float deltaX;
            float deltaY;

            // Mouse State & Keyboard State
            currentMouseState = Mouse.GetState();
            KeyboardState state = Keyboard.GetState();

            // Handle basic movement
            Vector3 moveVector = Vector3.Zero;

            if (state.IsKeyDown(Keys.W))
                moveVector.Z = 1;
            if (state.IsKeyDown(Keys.S))
                moveVector.Z = -1;
            if (state.IsKeyDown(Keys.A))
                moveVector.X = 1;
            if (state.IsKeyDown(Keys.D))
                moveVector.X = -1;
            if (state.IsKeyDown(Keys.Space))
                moveVector.Y = 1;
            if (state.IsKeyUp(Keys.Space) && Position.Y > 1.07)
                moveVector.Y = -1;

            if (moveVector != Vector3.Zero)
            {
                // Normalize vector so that we don't move faster diagonally
                // Turns it into a unit vector
                moveVector.Normalize();

                // Now we add in smooth factor and speed
                moveVector *= deltaTime * cameraSpeed;

                // Move camera
                MoveCamera(moveVector);
            }

            // Handle mouse movement
            if(currentMouseState != previousMouseState)
            {
                // Cache mouse location
                deltaX = currentMouseState.X - (device.Viewport.Width / 2);
                deltaY = currentMouseState.Y - (device.Viewport.Height / 2);

                // Create the rotation
                mouseRotationBuffer.X -= 0.01f * deltaX * mouseSensitivity;
                mouseRotationBuffer.Y -= 0.01f * deltaY * mouseSensitivity;

                // Clamp the rotation so it can't do a barrel roll
                if(mouseRotationBuffer.Y < MathHelper.ToRadians(-75.0f))
                    mouseRotationBuffer.Y = mouseRotationBuffer.Y - (mouseRotationBuffer.Y - MathHelper.ToRadians(-75.0f));
                if (mouseRotationBuffer.Y > MathHelper.ToRadians(75.0f))
                    mouseRotationBuffer.Y = mouseRotationBuffer.Y - (mouseRotationBuffer.Y - MathHelper.ToRadians(75.0f));

                Rotation = new Vector3(-MathHelper.Clamp(mouseRotationBuffer.Y, MathHelper.ToRadians(-75.0f), MathHelper.ToRadians(75.0f)),
                    MathHelper.WrapAngle(mouseRotationBuffer.X), 0);
            }

            // Center the mouse
            Mouse.SetPosition(device.Viewport.Width / 2, device.Viewport.Height / 2);

            // Save previous mouse state
            previousMouseState = currentMouseState;
        }
    }
}

```

# Answer
> 1 votes
Conceptually, in a third person camera game, all your movement and rotation algorithms would be in your player class (Update method) as you use WASD and mouse to move and rotate your player around, not the camera. This new position and rotation of the player is stored in a matrix which has 2 jobs: 1. it will be used during drawing of the player as effect.World. and 2. sent to the camera's Update method to locate and orient the 3rd person camera.

Once the player's matrix is established, It gets passed to the Camera Update which uses it to create a new **1st person view matrix** as follows:

```
void Update(Matrix playerWorldMatrix)
{

   Vector3 cameraPosition = playerWorldMatrix.Translation + (playerWorldMatrix.Backwards * cameraTrailingDistance);
   Vector3 cameraLookAt = playerWorldMatrix.Translation + (playerWorldMatrix.Forward * cameraLookAheadDistance);

   view = Matrix.CreateLookAt(cameraPosition, cameraLookAt, Vector3.Up);

}

```

The camera view matrix is that simple. But it can be adjusted to perfection also. It is easy to place vertical or horizontal offsets too so the camera is placed, say, over the right shoulder of the player looking forward:

```
Vector3 cameraPosition = playerWorldMatrix.Translation + (playerWorldMatrix.Backwards * cameraTrailingDistance) +
                                                         (playerWorldMatrix.Right * cameraRightLeftOffset) +
                                                         (playerWorldMatrix.Up * cameraVerticalOffset);

```

---
Tags: xna, camera, monogame, third-person-view
---


# Question
Title: Unity: How can I get the width of a gameobject?
I'm trying to make sure a gameobject (2D sprite, say, panda) stays to the left of another (say, bamboo), regardless of the former's size. I thought I could take the bamboo's location, and deduct the width of the panda from it.

Something like this:

Here's my code so far:

```
foreach (GameObject panda in midBambooStack)
{
    Vector3 newPosition = new Vector3(midBamboo.transform.position.x - panda.transform.lossyScale.x, panda.transform.position.y, panda.transform.position.z);
    panda.transform.position = newPosition;
}

```

But what I end up is that the panda goes right in the middle of the bamboo, so I'm assuming the `lossyScale.x` bit is wrong.

Any suggestions?

EDIT: Here's my hierarchy, if it means something.

# Answer
This will rely on the Pixel Per Unit value of your sprite. If you do not have a 1:1 ratio, then a value of "1" for your LocalScale.x will not be the same width as your sprite.

Either set the sprite's Pixel Per Unit value to a 1:1 ratio, or manually calculate the ratio multiplier:

```
float PixelUnits;

private void CalculatePixelUnits()
{
    PixelUnits = Sprite.rect.width / Sprite.bounds.size.x;
}

```

In the above code you would pass in your Panda sprite.

With this value you should then be able to position these Pandas properly:

```
foreach (GameObject panda in midBambooStack)
{
    Vector3 newPosition = new Vector3(midBamboo.transform.position.x - panda.transform.localScale.x * PixelUnits, panda.transform.position.y, panda.transform.position.z);
    panda.transform.position = newPosition;
}

```
> 3 votes

---
Tags: unity
---


title: Java - Shooting Towards Mouse Click

text:
# Question
Title: Java - Shooting Towards Mouse Click
I'm trying to get my bullet to shoot towards the mouse click but it just shoots directly towards the left from the players position here's the code i used:

**Game Class (Main)**

```
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.swing.JFrame;
public class Game extends JFrame implements KeyListener, MouseListener
{
    public Player player;
    private Image image;
    private Graphics graphics;

    public int MouseX;
    public int MouseY;

    private Font Title = new Font("SansSerif",Font.BOLD,20);
    private Font SubTitle = new Font("SansSerif",Font.BOLD,16);
    private Font Text = new Font("SansSerif",Font.PLAIN,11);

    public boolean playerUp = false;
    public boolean playerDown = false;
    public boolean playerLeft = false;
    public boolean playerRight = false;

     CopyOnWriteArrayList<Bullet> bullets = new CopyOnWriteArrayList();

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

    public Game(){

        //Properties of JF
        setTitle("Ninjaa Fight!");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(697,670);
        setResizable(false);
        setVisible(true);
        addKeyListener(this);
        addMouseListener(this);
        setLocationRelativeTo(null);

        //Properties of P
        player = new Player(150,520,90,90,100, "Images/Back S..jpg");
    }
    public void paint(Graphics g){

        image = createImage(getWidth(), getHeight());
        graphics = image.getGraphics();
        paintComponent(graphics);
        g.drawImage(image, 0, 0, null);
        repaint();
        g.drawRect(50, 50, 400, 570);
        g.setFont(Title);
        g.drawString("Ninjaa Fight!", 530, 70);
        g.setFont(SubTitle);
        g.drawString("Status", 530, 100);
        g.setFont(Text);
        g.drawString("Health: " + player.health, 530, 120);
        g.drawString("x Position: " + player.xPos, 530, 135);
        g.drawString("y Position: " + player.yPos, 530, 150);
        g.drawString("Enemies Total: " + "5", 530, 165);
        g.drawString("Enemies Defeated: " + "0", 530, 180);
        g.drawString("Enemies Left: " + "5", 530, 195);
        g.drawString("Level: " + "1", 530, 210);
        g.drawString("Player: " + "Guang Hu An", 530, 225);
        g.setFont(SubTitle);
        g.drawString("Instructions", 530, 255);
        g.setFont(Text);
        g.drawString("Up: W", 530, 275);
        g.drawString("Down: S", 530, 290);
        g.drawString("Left: A", 530, 305);
        g.drawString("Right: D", 530, 320);
        g.drawString("Shoot: L", 530, 335);
        g.drawString("Hit: K (Comming Soooon)", 530, 350);
        g.drawString("Switch Player: J (Comming Soon)", 530, 365);

        g.drawString("Credits: Areeb Raza - Designer, Coder and Programmer", 50, 640);
        g.drawString("Copyright © 2015 by Areeb Raza", 50, 655);
    }

    public void paintComponent(Graphics g){

        player.draw(g);
        player.update(this);

        for(Bullet bullet : bullets){
            bullet.draw(g);
            bullet.update(this);
        }

    }

    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == e.VK_W){
            playerUp = true;
        }
        if(e.getKeyCode() == e.VK_S){
            playerDown = true;
        }

        if(e.getKeyCode() == e.VK_A){
            playerLeft = true;
        }
        if(e.getKeyCode() == e.VK_D){
            playerRight = true;
        }

    }

    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub
        if(e.getKeyCode() == e.VK_W){
            playerUp = false;
        }
        if(e.getKeyCode() == e.VK_S){
            playerDown = false;
        }

        if(e.getKeyCode() == e.VK_A){
            playerLeft = false;
        }
        if(e.getKeyCode() == e.VK_D){
            playerRight = false;
        }

    }

    @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub

         Bullet playerBullet = new Bullet(-1, player.getxPos(),  player.getyPos(), 10, 10, "Images/Ninja Star.jpg");
            bullets.add(playerBullet);

        MouseX = e.getX();
        MouseY = e.getY();
        System.out.println("(" + MouseX + ", " + MouseY + ")");

    }
    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub

    }
}

```

**Bullet Class**

```
import java.awt.*;
public class Bullet extends GameObject {
    private int deltaY;
    public double xVelocity;
    public double yVelocity;
    public double angle;
    public Bullet (final int deltaY, final int xPos, final int yPos, final int width, final int height,  final String img) {
        this.deltaY = deltaY;
        this.xPos = xPos;
        this.yPos = yPos;
        this.img = getImage(img);
        this.width = width;
        this.height = height;

        }

    public void draw(Graphics g) {
            g.drawImage(img, xPos, yPos, width, height, null);

        }

        void update(final Game g) {
            double bulletVelocity = 1.0; //however fast you want your bullet to travel
            //mouseX/Y = current x/y location of the mouse
            //originX/Y = x/y location of where the bullet is being shot from
             angle = Math.atan2(g.MouseX - g.player.getxPos(), g.MouseY - g.player.getyPos());
             xVelocity = (bulletVelocity) * Math.cos(angle);
             yVelocity = (bulletVelocity) * Math.sin(angle);
            xPos += xVelocity;
            xPos += yVelocity;

        }

    public int getDeltaY() {
        return deltaY;
    }

    public void setDeltaY(int deltaY) {
        this.deltaY = deltaY;
    }

    @Override
    Image getImage(String img) {
        // TODO Auto-generated method stub
        return Toolkit.getDefaultToolkit().getImage(img);
    }
    }

```

# Answer
I think you have a copy/paste bug here:

```
xPos += xVelocity;
xPos += yVelocity;

```

The last line should probably be

```
yPos += yVelocity;

```
> 1 votes

---
Tags: java
---


# Question
Title: Why do I get this error about DllMain when using D3D from within a DLL?
I am trying to create a Dll that will handle all my rendering, I am trying to initialize Direct X but I am getting the following error message:

> DXGI ERROR: CreateDXGIFactory cannot be called from DllMain. \[ MISCELLANEOUS ERROR #76: \] Exception thrown at 0x00007FF978181F28 in Engine.exe: Microsoft C++ exception: \_com\_error at memory location 0x000000541631BE90.

I never directly call CreateDXGIFactory, I only call D3D11CreateDevice before the program crashes, here is the code for D3D11CreateDevice:

```
HRESULT hRes;
    D3D_FEATURE_LEVEL featureLevel;
    m_pConsole->WriteToConsole("Creating D3D11 device !");
    hRes = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, D3D11_CREATE_DEVICE_DEBUG, NULL, 0, D3D11_SDK_VERSION, &m_pD3D11Device, &featureLevel, &m_pD3D11DeviceContext);

```

This function call is not in Dll main it is in an initialize function that is in its own class within the Dll.

# Answer
You cannot call `DXGICreateFactory` directly (or indirectly) from `DllMain` because the load order of dependent DLLs cannot be guaranteed. Loading DXGI can demand the load of other DLLs depending on OS and driver versions, and that can result in crashes or deadlocks (due to the loader lock).

> I only call D3D11CreateDevice before the program crashes... This function call is not in Dll main it is in an initialize function that is in its own class within the Dll.

D3D11CreateDevice will indirectly need to initialize DXGI.

Verify that this initialization function is not called by any constructors of global objects, as those constructors are executed for those globals just prior to `DllMain` and suffer the same order-of-operations problems.

Generally you should provide an explicit entry point to your DLL, such as `InitializeRendering` or whatnot, that invokes any code that will need to directly or indirectly load DLLs or do anything scary that shouldn't be done in `DllMain`.
> 4 votes

---
Tags: c++, directx, directx11, dll
---


title: How to optimize against wealth loss?

text:
# Question
Title: How to optimize against wealth loss?
The wealth system in d20 Modern always gives me a slight headache at character creation, because I know there's a better way to buy things, but I don't know exactly how, so I'm coming up with an algorithm to automatically buy things in the correct order to minimize losses, sticking it in a program, and just stop thinking about the whole thing. Help if you can, pls.

---

Algorithm

\[Wealth is your Wealth Bonus, and DC is the Purchase DC of the item on the list. \> is greater than, \< is less than, \>= is greater than or equal to, and \<= is less than or equal to\]

Wealth is a random value generated at the beginning (let's say 1 to 100), and the list of items purchased can contain up to 25 items of equally random purchase DCs. Just in case that's relevant. In the link above, it mentions things like 1d6 and 2d6. In the format xdy, x= number of dice rolled, and y = number of sides each dice have. So 2d6 would generate a number from 2 to 12. 1d6 would generate one from 1 to 6.

-

Run the following through all items in the list first, since if the following conditions are met, the item is free, but might not remain free if you lose wealth:

If DC \<15 and (Wealth - DC) \> 0 Purchase item

-

Then, determine if there are items on the list that would jump up a tier if you lost 1 wealth (So, if Wealth - DC = -10 or -15) \[Don't check for Wealth - DC = 0, because it should have already been bought if it was.\]

If there isn't, then purchase an item with DC \>=15 and (Wealth - DC) \> 0

Repeat that until there are either no more items fitting the conditions, or until you are on the verge of jumping up a tier.

-

(I haven't figured out how to optimize against tier-jumping. I'm inclined to immediately buy anything that might tip over in to -16 territory, and abandon anything that ends up there. If there are none, then prioritize any in the threat of going over a tier, and abandon any that might go in to the -16+ territory. There's some way to better formulate around these tiers, but it's rather mind-racking, and frustrating that I can't seem to figure it out!.)

-

Repeat the last process (that I actually outlined), but determining if items would jump up a tier if you lost 2 wealth If there isn't, then purchase an item with DC\>=15 and (Wealth - DC) \< 0 and (Wealth - DC) \> -11 (I have no idea where in the queue I should put this, but I just felt like this would be the lowest priority purchase.)

If an item comes with a restriction of +2 or greater (and you only care about the wealth you have at the end), then, unless the black market adjustment pushes the item over a tier, take the black market because you don't lose as much wealth that way. If it's only +1, then take the license unless you have 9 wealth or less, in which case obey the previous rule on restriction.

# Answer
`but I don't know exactly how` / `just stop thinking about the whole thing`

Provided that you don't need to know how the algorithm ultimately *works*, but only need to *do the job*, you might look into Genetic Algorithms. It is a highly iterative process that starts with a random genome per candidate, and, using an analogue to natural selection, slowly converges from those initial inputs toward an approximately optimal solution. The catch is that you must provide a fitness function by which to judge the genes of each successive generation. In your case this would be an evaluation of how much money was spent by each candidate (gene set). You do this for say 100 sets of virtual "genes", look at the best ones as judged by your fitness function(s), and perform gene crossover and mutation to arrive at the next generation of 100. These will gradually improve. "Genes" are either a random sequence of bits or some variables randomised each run.

**Important:** You must make sure that your genes represent some *behaviour* of your code, not some *state*. This is crucial, or you won't be able to converge on a solution. The change in a gene needs to be directly proportional to some measure of failure / success. See top answer here.

Rinse, repeat till you are happy with result. This process can be fully automated in code.

Genetic Programming may also be useful; though I doubt it will be necessary in your case - as I imagine you only need your parameters to evolve - not your code as such.

These are large topics so I will not go further here. Refer there for a simple starter tutorial.
> 1 votes

---
Tags: algorithm
---


# Question
Title: Efficiently culling off-screen objects on a top-down 2D map
I know efficiency is key in game programming and I've had some experiences with rendering a "map" earlier but probably not in the best of ways.

**For a 2D TopDown game:** (simply render the textures/tiles of the world, nothing else)

Say, you have a map of 1000x1000 (tiles or whatever). If the tile isn't in the view of the camera, it shouldn't be rendered - it's that simple. No need to render a tile that won't be seen. But since you have 1000x1000 objects in your map, or perhaps less you probably don't want to loop through all 1000\*1000 tiles just to see if they're suppose to be rendered or not.

**Question:** What is the best way to implement this efficiency? So that it "quickly/quicker" can determine what tiles are suppose to be rendered?

Also, I'm not building my game around tiles rendered with a SpriteBatch so there's no rectangles, the shapes can be different sizes and have multiple points, say a curved object of 10 points and a texture inside that shape;

**Question:** How do you determine if this kind of objects is "inside" the View of the camera?

It's easy with a 48x48 rectangle, just see if it X+Width or Y+Height is in the view of the camera. Different with multiple points.

Simply put, how to manage the code and the data efficiently to not having to run through/loop through a million of objects at the same time.

# Answer
> 6 votes
As for *complex* objects I think the best way is just to reduce them to surrounding rectangles, and check if that rectangle is inside the viewport. Even if you will render a texture which is not actually visible (because of it's shape) it's still will be probably faster than doing a more complex detection algorithm.

As for handling large maps efficiently you should subdivide your map on larger scale, say 10x10. Then you check your viewport intersection. In worst case it hits 4 this 'regions' which will result in (100x100)\*4 = 40K objects. This is a simplified example. For a real usage you should consider Quadtree structure which is especially efficient for such subdivisions and collision detection (viewport visibility check is basically collision check between viewport and sprite).

# Answer
> 3 votes
When you have many mobile objects, you should store them by their coordinates in a multi-dimensional tree structure. That way you can efficiently get a list of all objects which are inside a given rectangle. You can even get them ordered by their x- or y-coordinates, which is important for drawing order when object sprites overlap.

This will also come in very handy for collision detection.

See the wikipedia article about k-d trees for details.

When 2d trees are too complicated for you, there is also an easier but not much less effective alternative: Store the objects as children of the tiles. When you move an object, you remove it from the object list of its old tile, and put it into the object list of the new one. When you draw the objects, you again iterate over the tiles in the viewport and retrieve their objects. Then you sort them all by y-coordinates and draw them.

# Answer
> 1 votes
Don't know if it is the best way, but this is how I learn to do it:

you have an two-dimensional array of "tiles"

```
public Tile tilemap[][];

```

and you decide the position of the "camera" with a Vector2, you will only render what is inside the scene, the big rectangle is what you can see on the screen, is useless to draw the rest of the scene.

Now you need to get the offsets, assuming you want your camera to be at the center of the scene:

```
offsetX = (graphics().width() / 2 - Math.round(cam.Position().X));
offsetX = Math.min(offsetX, 0);
offsetX = Math.max(offsetX, graphics().width() / 2 - mapWidth);
offsetY = (graphics().height()) / 2 - Math.round(cam.getPosition().Y);
offsetY = Math.min(offsetY, 0);
offsetY = Math.max((graphics().height() / 2 - mapHeight), offsetY);

```

now, in which part of the array the visible tiles start and finish?

```
firstTileX = pixelsToTiles(-offsetX);

lastTileX = firstTileX + pixelsToTiles(graphics().width());

firstTileY = pixelsToTiles(-offsetY);

lastTileY = firstTileY + pixelsToTiles(graphics().height());

int pixelsToTiles(int pixels) {
    return (int) Math.floor((float) pixels / Tile.getHeight());
}

```

and in your draw method, you just loop through the visible part of the array:

```
   for (int x = firstTileX; x < lastTileX; x++) {
        for (int y = firstTileY; y < lastTileY; y++) {
              Vector2 position = new Vector2(tilesToPixelsX(x) + offsetX,
                        tilesToPixelsY(y) + offsetY);
              tilemap[x][y].Draw(surf, position);
        }
    }

```

# Answer
> 0 votes
You can have one Bitmap that is the whole scene but not displayed. And then a displayed screen sized camera layer Bitmap that just draws from the whole scene but only the part that needs to be shown.

---
Tags: xna, rendering, maps, culling
---


title: JavaFX snake game AI

text:
# Question
Title: JavaFX snake game AI
I am trying to add an AI simulated snake to my snake game that a player can play against. So far I think I do get the concept of how to do certain things but snake should be able to find the nearest apple and collected. it has to also be able to avoid colliding with itself and with objects through out the scene. I know this is hard to do. I have created some simple algorithms to make the AI find the clossest apple and collect it. the algorithm sometimes fails to make the right turns in order to collect the nearest apple.

the snake also has the possibility to teleport to the opposite sides of the scene. I have difficulty calculating when the snake should decide that it would be fastest to teleport since it would be faster to obtain an apple located at the other side. maybe a condition that checks if the distance between the snake and the clossest apple is greater than the distance between the snake and the border + (apple - oppsite border).

anyways here is a sample video of what the snake could do ATM: https://youtu.be/1SRV2gyhLxw

Here is the code that controlls the snake.

```
/**

 * @author Eudy Contreras
 *
 */
public class PathFindingAI {

    private AbstractObject objective;
    private AbstractTile obstacle;
    private GameManager game;
    private PlayerTwo snakeAI;
    private Random rand;

    private boolean makingUTurn = false;

    private double positionX = 0;
    private double positionY = 0;
    private double turnOffset = 100;

    private int randomBoost = 200;

    private ObjectivePosition location;

    public PathFindingAI(GameManager game, PlayerTwo snakeAI) {
        this.game = game;
        this.snakeAI = snakeAI;
        initialize();
    }

    public void initialize() {
        rand = new Random();
    }

    public void findObjective() {
        if (game.getModeID() == GameModeID.LocalMultiplayer)
            createPath(objective);

    }
    /*
     * Gets called when the game begins in order
     * to initiate the simulation
     */
    public void startSimulation() {
        if (game.getModeID() == GameModeID.LocalMultiplayer)
            createPath(findClosest());
    }
    /*
     * this method gets called from the game loop and it
     * is called at 60fps. The method update and keeps track
     * of things
     */
    public void updateSimulation() {
        if (game.getModeID() == GameModeID.LocalMultiplayer) {
            if (game.getStateID() == GameStateID.GAMEPLAY && objective != null) {
                checkCurrentLocation();
                addRandomBoost(true);
                checkObjectiveStatus();
                reRoute();
            }
        }
    }
    /**
     * Method which under certain conditions will activate
     * the speed boost of the snake
     * @param random
     */
    public void addRandomBoost(boolean random) {
        if (random && rand.nextInt(randomBoost) != 0) {
            return;
        }
        if (snakeAI != null) {
            if (game.getEnergyBarTwo().getEnergyLevel() > 50) {
                snakeAI.setSpeedThrust(true);
            } else {
                snakeAI.setSpeedThrust(false);
            }
        }

    }
    /**
     * Method which when called will attempt to find the apple which is closest
     * to the current position of the snake!
     * @return
     */
    private AbstractObject findClosest() {

        Distance[] distance = new Distance[game.getGameObjectController().getFruitList().size()];

        for (int i = 0; i < game.getGameObjectController().getFruitList().size(); i++) {
            distance[i] = new Distance(
                    Math.hypot(snakeAI.getX() - game.getGameObjectController().getFruitList().get(i).getX(),
                            snakeAI.getY() - game.getGameObjectController().getFruitList().get(i).getY()),
                    game.getGameObjectController().getFruitList().get(i));
        }

        double closest = distance[0].getDistance();

        for (int i = 0; i < distance.length; i++) {
            if (distance[i].getDistance() < closest) {
                closest = distance[i].getDistance();
            }
        }
        for (int i = 0; i < distance.length; i++) {
            if (distance[i].getDistance() == closest) {
                if (distance[i].getObject().isAlive()) {
                    objective = distance[i].getObject();
                    positionX = distance[i].getObject().getX();
                    positionY = distance[i].getObject().getY();
                }
            }
        }
        if (objective != null)
            objective.blowUpAlt();
        return objective;
    }
    /**
     * Method which gets called in the update method and
     * will create a new path after the snake has perform
     * a uTurn!
     */
    private void reRoute() {
        if (makingUTurn) {
            turnOffset--;
            if (turnOffset <= 0) {
                makingUTurn = false;
                createPath(objective);
            }
        }
    }

    @SuppressWarnings("unused")
    private void log(String str) {
        System.out.println(str);
    }
    /*
     * Method which attempts to determine the best course of action in order
     * to move towards the objective. The method will first check if the x distance
     * is less or greater than the y distance and based on that it will decide to perform
     * a horizontal or vertical move.  if the method to be perform is a vertical move
     * the method will check if the objective is above or below and then perform a move
     * based on the objectives coordinates.
     */
    private void createPath(AbstractObject objective) {
        if (Math.abs(snakeAI.getX() - objective.getX()) < Math.abs(snakeAI.getY() - objective.getY())) {
            if (objective.getY() > snakeAI.getY()) {
                location = ObjectivePosition.SOUTH;
                performMove(PlayerMovement.MOVE_DOWN);
            }
            else{
                location = ObjectivePosition.NORTH;
                performMove(PlayerMovement.MOVE_UP);
            }
        } else {
            if (objective.getX() > snakeAI.getX()) {
                location = ObjectivePosition.EAST;
                performMove(PlayerMovement.MOVE_RIGHT);
            }
            else{
                location = ObjectivePosition.WEST;
                performMove(PlayerMovement.MOVE_LEFT);
            }
        }
    }
    /**BUGGGY!!
     *
     * This method attempts to determine a course of action once a special bound has intersected any
     * obstacle. the method attempts to determine what action the snake should take base on the position
     * of the snake relative to the coordinates and dimensions of the obstacle encountered. The method does
     * not work as intended. NEED HELP =(
     *
     * @param obstacle
     */
    public void avoidObstacle(AbstractTile obstacle) {
        this.obstacle = obstacle;
        if (game.getModeID() == GameModeID.LocalMultiplayer) {
            switch (snakeAI.getCurrentDirection()) {
            case MOVE_DOWN:
                if ((obstacle.getBounds().getWidth()+obstacle.getBounds().getMinX()) - (snakeAI.getHead().getRadius()+snakeAI.getX())> obstacle.getBounds().getWidth()/2){
                    snakeAI.setDirection(PlayerMovement.MOVE_LEFT);
                }
                else{
                    snakeAI.setDirection(PlayerMovement.MOVE_RIGHT);
                }
                    break;
            case MOVE_LEFT:
                if((obstacle.getBounds().getHeight()+obstacle.getBounds().getMinY()) - (snakeAI.getHead().getRadius()+snakeAI.getY())> obstacle.getBounds().getHeight()/2){
                    snakeAI.setDirection(PlayerMovement.MOVE_UP);
                }
                else{
                    snakeAI.setDirection(PlayerMovement.MOVE_DOWN);
                }
                break;
            case MOVE_RIGHT:
                if((obstacle.getBounds().getHeight()+obstacle.getBounds().getMinY()) - (snakeAI.getHead().getRadius()+snakeAI.getY())> obstacle.getBounds().getHeight()/2){
                    snakeAI.setDirection(PlayerMovement.MOVE_UP);
                }
                else{
                    snakeAI.setDirection(PlayerMovement.MOVE_DOWN);
                }
                break;
            case MOVE_UP:
                if ((obstacle.getBounds().getWidth()+obstacle.getBounds().getMinX()) - (snakeAI.getHead().getRadius()+snakeAI.getX())> obstacle.getBounds().getWidth()/2){
                    snakeAI.setDirection(PlayerMovement.MOVE_LEFT);
                }
                else{
                    snakeAI.setDirection(PlayerMovement.MOVE_RIGHT);
                }
                break;
            case STANDING_STILL:
                break;
            default:
                break;

            }
        }
    }
    /**
     * Method which performs actions based on the current location of the snake and the objective.
     * if the snake is within a predetermined threshold the snake will perform the appropriate turn
     * in order to collect the objective.
     */
    private void checkCurrentLocation() {
            if (snakeAI.getX() > objective.getX() - objective.getRadius() / 2 && snakeAI.getX() < objective.getX() + objective.getRadius() / 2) {
                if (objective.getY() < snakeAI.getY()) {
                    snakeAI.setDirection(PlayerMovement.MOVE_UP);
                } else {
                    snakeAI.setDirection(PlayerMovement.MOVE_DOWN);
                }
            }
            else if (snakeAI.getY() > objective.getY() - objective.getRadius() / 2 && snakeAI.getY() < objective.getY() + objective.getRadius() / 2) {
                if (objective.getX() < snakeAI.getX()) {
                    snakeAI.setDirection(PlayerMovement.MOVE_LEFT);
                } else {
                    snakeAI.setDirection(PlayerMovement.MOVE_RIGHT);
                }
            }
    }
    /**
     * Method which checks the status of the current objective and base on the objective's status it will try
     * to re-determine a new objective once the current objective has been collected or it has moved!
     */
    private void checkObjectiveStatus() {
        if (!objective.isAlive()) {
            findClosest();
            createPath(objective);
        }
        if (objective.getX() != positionX || objective.getY() != positionY) {
            findClosest();
        }
    }
    /**
     * Method which when called will determine if the snake has to make an u-turn or
     * if the snake can perform the desired turn without complications! NEEDS ANALYSIS!!!!
     * @param move: Move which the AI desires to perform
     */
    private void performMove(PlayerMovement move) {
        if (move == PlayerMovement.MOVE_UP && snakeAI.getCurrentDirection() == PlayerMovement.MOVE_DOWN) {
            makeUTurn(snakeAI.getCurrentDirection());
        } else if (move == PlayerMovement.MOVE_DOWN && snakeAI.getCurrentDirection() == PlayerMovement.MOVE_UP) {
            makeUTurn(snakeAI.getCurrentDirection());
        } else if (move == PlayerMovement.MOVE_LEFT && snakeAI.getCurrentDirection() == PlayerMovement.MOVE_RIGHT) {
            makeUTurn(snakeAI.getCurrentDirection());
        } else if (move == PlayerMovement.MOVE_RIGHT && snakeAI.getCurrentDirection() == PlayerMovement.MOVE_LEFT) {
            makeUTurn(snakeAI.getCurrentDirection());
        } else {
            snakeAI.setDirection(move);
        }
    }
    /**
     * Method which when called will perform a turn based on the location of the objective! once the turn
     * is made the path will be recalculated by the reRoute method! The method only gets called when the snake
     * attempts to perform an illegal turn!
     * @param currentDirection
     */

    private void makeUTurn(PlayerMovement currentDirection) {
        if (currentDirection == PlayerMovement.MOVE_DOWN || currentDirection == PlayerMovement.MOVE_UP) {
            if (objective.getX() < snakeAI.getX()) {
                snakeAI.setDirection(PlayerMovement.MOVE_LEFT);
                makingUTurn = true;
                turnOffset = snakeAI.getRadius();
            } else {
                snakeAI.setDirection(PlayerMovement.MOVE_RIGHT);
                makingUTurn = true;
                turnOffset = snakeAI.getRadius();
            }
        } else if (currentDirection == PlayerMovement.MOVE_RIGHT || currentDirection == PlayerMovement.MOVE_LEFT) {
            if (objective.getY() < snakeAI.getY()) {
                snakeAI.setDirection(PlayerMovement.MOVE_UP);
                makingUTurn = true;
                turnOffset = snakeAI.getRadius();
            } else {
                snakeAI.setDirection(PlayerMovement.MOVE_DOWN);
                makingUTurn = true;
                turnOffset = snakeAI.getRadius();
            }
        }
    }
    /**
     * Class which holds the distance and the nearest object
     * and the object!
     * @author Eudy Contreras
     *
     */
    private class Distance {

        private Double distance;
        private AbstractObject object;

        public Distance(double distance, AbstractObject object) {
            this.distance = distance;
            this.object = object;
        }

        public double getDistance() {
            return distance;
        }

        public AbstractObject getObject() {
            return object;
        }
    }
    public void setPlayer() {
        this.snakeAI = null;
        this.snakeAI = game.getGameLoader().getPlayerTwo();
    }

    public ObjectivePosition getLocation() {
        return location;
    }

    public void setLocation(ObjectivePosition location) {
        this.location = location;
    }

    public AbstractTile getObstacle() {
        return obstacle;
    }

    public void setObstacle(AbstractTile obstacle) {
        this.obstacle = obstacle;
    }

    private enum ObjectivePosition {
        NORTH, SOUTH, WEST, EAST
    }
}

```

I will deeply appreciate any suggestions and help on solving these problems!

# Answer
You need to think about your game board as a potentially endless plane. For this imagine your board is in the center of a larger field, made of 9 copies of yours, in a 3x3 stack. So for each apple with coordinates (x,y), you have 8 more copies with coordinates like this:

```
(x-w, y-h) (x, y-h) (x+w, y-h)
(x-w, y)   (x, y)   (x+w, y)
(x-w, y+h) (x, y+h) (x+w, y+h)

```

So, you need to calculate distances to all of those copies in the findClosest() function, 9 distances for each apple.
> 1 votes

---
Tags: java, ai, game-mechanics, path-finding, javafx
---


title: Quake style snapshot system for an MMO?

text:
# Question
Title: Quake style snapshot system for an MMO?
I'm making an MMO style game in my spare time for kicks, I've been researching more and more into networking for video games and I've mostly been learning about Quake and Sources networking implementation where they have an authoritative server with a snapshot system where the client receives snapshots that reflect the current state, and the clients will send their input to the server and the server will simulate the game, etc.

Is this what most MMO games use in terms of their networking? I ask this because as I'm implementing it, it seems very expensive if you want a lot of players\*, whereas the networking architecture seems more like it was designed for Quake or Source games where it's mostly shooter type stuff where you only have maybe 10 players at a time, sometimes you have 30 or so.

* To elaborate here, I mean that having even 10 players it costs a lot to send snapshots back and forth in terms of bandwidth, it can pretty quickly add up to megabytes. Is this normal? Is this expensive? I don't do a lot of network programming so I'm not particularly sure what is cheap or expensive in terms of bandwidth.

I've currently implemented most of this system, though I've added regions so that the world is split up into multiple areas so that entities in region A don't care about the events, particles, and other entities, etc. in region B or C, D, and so on.

# Answer
> 1 votes
You simply don't send the whole snapshot, but only the relevant information.

The map, the 3D architecture, the client is supposed to know that, no need to send it everytime, just tell him he need to load the file levelX.3d.

And so on so forth, until you only send the information that are important / usefull if faked, usually the position of each player, their direction, and their actions.

With the position and direction, you can predict client side where each player will be on the next few frame, their action to know if you need to use a animation.

The client refresh the data based on what the server tell him, this is why on a bad network, you see player "teleporting", it's just the client rectifying the information.

The client don't send the whole snapshot either, but only his position, direction and action, the server verify if the data is coherent (if the player teleported...), and send him back the information of all the over player.

---
Tags: networking, mmo
---


# Question
Title: How do I load scene using scene manager build index in the build setting unity3d
I only got one scene to load when the timer reaches zero; I need one more scene to load. The scene manager builder index is not working for me. I have tried `Application.Load()` and `SceneManager.Load()`, but nothing works.

I can only reload the other scene with the following line of code, but it reloads the current scene, and I don't want it to do that.

```
SceneManager.LoadScene(SceneManager.GetActiveScene().name);

```

The scene I am trying to reload is my restart. It's suppose to load the scene I have set up in the build settings. It's also suppose to load when the timer reaches a set time, and does that, but only with the previous line of code.

Here is the rest of my code:

```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class TestScript : MonoBehaviour
{
    public MyClockScript myClock;
    public ScoreManagerScript scoremanager;
    public int scoreToReach = 99; // change this value to what you want
    public string nextScene = "FY"; // change this value to what you want

    void Update ()
     {
       if (myClock.m_leftTime <= 0)
       {
         if ((ScoreManagerScript.score >= scoreToReach) && (nextScene != ""))
         {
           SceneManager.LoadScene(nextScene);
         }
         else
         {
           int gy = SceneManager.GetActiveScene().buildIndex;
         }
       }
     }
 }

```

Help would be appreciated. I have a picture of what I scene I want to load, too.

# Answer
This code works fine. The only issue is at the bottom, where you have another `LoadScene()` which uses the index `2`. Even with the code as it is, I am able to load scenes "FY" and "GY".

```
void Update ()
{
    if (myClock.m_leftTime <= 0)
    {       //checking if there is a next scene
        if ((ScoreManagerScript.score >= scoreToReach) &&
            (SceneManager.GetActiveScene ().buildIndex + 1 <
                                   SceneManager.sceneCountInBuildSettings))
        {
            //load scene with next scene index
            SceneManager.LoadScene (SceneManager.GetActiveScene ().buildIndex + 1);
            // SceneManager.LoadScene (nextScene);
            Debug.Log ("We are inside next scene if");
        }
        else
        {
            //load scene with current scene index/general reload
            SceneManager.LoadScene (SceneManager.GetActiveScene ().buildIndex);
        }

        //load scene with next scene index
        SceneManager.LoadScene (SceneManager.GetActiveScene ().buildIndex + 2);
        // Because this last load scene doesn't have a condition statement,
        // the script loads index 1, and than index 2.
    }
}

```

---

### Unrelated issue with enemies

Also, when running the game ,there was an `out-of-range` on your `EnemiesSpawner.cs`. I fixed it by doing the below;

```
for (int spawnCount = 0; spawnCount > 20; spawnCount++)
{
            Instantiate (enemy, spawnPoints [spawnPointIndex].position,
                                                   spawnPoints [spawnPointIndex].rotation);
}

```

In addition, you might want to randomize how the enemies are spawned, as every time I started the game they spawn at the same location. Game looks great, by the way! Good luck.
> 1 votes

---
Tags: unity, c#, scenemanager
---


# Question
Title: Set Parent to Instantiated Objects in Unity
i am having problem in attaching parent to the instantiated objects. I have attached the code below. please tell me where i am doing wrong. Thank you.

```
public GameObject brick;
public Transform BrickHolder;
//public GameObject Bricks;

void Start(){
    for (float y = 2.16f; y < 4.88f; y += 0.34f){
        for (float x = -2.125f; x <= 2.125f; x += 0.85f){

            GameObject Bricks = Instantiate(brick, new Vector3(x, y, 0), Quaternion.identity) as GameObject;

            if (Bricks != null) {
                Debug.Log("Hello");
                Bricks.transform.SetParent(BrickHolder);
            }

        }
    }
}

```

# Answer
I have personally never used `SetParent()`. I have always used the `parent` property, like so:

```
Bricks.transform.parent = BrickHolder;

```

This should be pretty much equivalent though, so I don't expect that is the issue *(confirmed in comments already)*. The difference is that `SetParent()` allows you to update the child transform in relation to the parent, or not (with the second boolean parameter: `worldPositionStays`).

Update:
If `BrickHolder` is `null`, Unity will happily accept it without error, since it's valid to unparent a child object. Make sure that `BrickHolder` has been assigned.

Update2:
If `Bricks` is also `null`, that would suggest that `brick` is not valid (probably also `null`). You will need to make sure both `brick` and `Brickholder` have been assigned to your component in the inspector or through another script.

The only other suggestion I can offer is that sometimes you need to reset your component (the one in your question) in the inspector or remove and reattach. Sometimes Unity doesn't update the serialized values if it thinks they haven't changed, so may be referencing invalid objects.
> 1 votes

# Answer
No need to add an assignment or setter call to establish the parent relationship. Simply, specify the fourth, `parent` argument for `Instantiate`, which, if supplied, needs to be a `Transform`. See it in the Unity docs.
> 1 votes

# Answer
The only way I could replicate the issue your having is by the "BrickHolder" variable being unassigned. I would make sure that it is assigned in the inspector.
> 0 votes

---
Tags: unity, gameobject
---


# Question
Title: What can I do to ensure that everyone can run my OpenGL game?
I am currently learning OpenGL from here. That website teaches OpenGl 3.3 with GLSL 3.3 and says that it is best to learn those because they are well supported and that older versions work in a less efficient way.

So far, this has been going well, but, when I tried to get my OpenGl programs to run on my laptop with Intel HD Graphics 3000, I ran into issues with the lack of GLSL 3.3 support (glGetShaderiv() and such claim that GLSL 3.3 is unavailable. When I ignore these errors, anything beyond the background color isn't rendered).

I am learning OpenGl in order to create a video game for which my target market will contain *many* older non-gaming computers (in addition to users with brand-new GTX 1080s). It wouldn't surprise me if a few users were still on Windows XP. It is essential that I make sure that everyone can run my game without buying extra hardware. It is equally essential that it looks good on hardware that can support it. What single, non-deprecated graphics API is available on all hardware (using software emulation if needed) along with Windows, Mac, and Linux?

If no single such API is available, what can I do to ensure that my game will work properly everywhere while also taking advantage of new features when available without learning multiple APIs? I would strongly prefer to stay close to the hardware by avoiding higher level APIs such as Ogre3D. If to do this I need to learn multiple APIs, then, what are those and why hasn't the industry standardized this by creating an API then releasing drivers for old hardware?

Some possible solutions are:

* A well-enough-performing software implementation of OpenGL 3.3 along with GLSL 3.3
* A OpenGL 3.3 implementation that uses OpenGL 1.0 in the background that can be easily swapped out automatically at runtime if newer versions aren't directly available.
* A simple to use older version of GLSL that allows me to load separate shaders as needed.

# Answer
> 6 votes
> What can I do to ensure that everyone can run my OpenGL game?

Nothing.

> What single, non-deprecated graphics API is available on all hardware (using software emulation if needed) along with Windows, Mac, and Linux?

There's no such API.

> ...why hasn't the industry standardized this by creating an API then releasing drivers for old hardware?

The industry is competitive and graphics hardware evolves. In the particular case of graphics hardware, it's evolution is quite different to that of CPUs. An API that is suitable for graphics hardware of 10 years ago is completely unsuitable for graphics hardware of today.

> A well-enough-performing software implementation of OpenGL 3.3 along with GLSL 3.3

There's no such thing.

---

These are probably not the answers you wanted to hear, but they are a truth you're going to have to accept: **wanting to support all users on all hardware with all operating systems is an unrealistic objective** \- doubly so if you're just learning.

---

Despite all of this there are a number of options open to you:

**Pick a minimum OpenGL version that's lower than 3.3**

The older Intel HD graphics (HD 2000, HD 3000) support OpenGL 3.1, which will get you most of the same functionality as OpenGL 3.3.

**Use OpenGL 3.3 Anyway**

Realistically, if you're only learning now you're at least a year or two away from releasing. By the time you release many of your target users will have upgraded their hardware, so the chances of someone not having support for 3.3 are lower.

**Use Direct3D instead**

Driver support from the vendors is much better (you would have D3D11 on the HD 2000/3000) but of course you're limiting yourself to Windows only.

**Use an engine like Unity or Unreal instead**

These have already done all of the hard work of supporting multiple APIs and multiple OSs for you, so you can focus on just creating your game.

**Change your objectives and accept not being able to support everybody**

As I said earlier, you have an unrealistic objective here. You're learning OpenGL, you're making your first game, but yet you want to support everybody on all hardware and all OSs. That's just not going to happen. You're going to give yourself a *significantly higher* change of succeeding if you narrow your scope.

Even if you choose one of the other options, you should give this serious consideration anyway.

# Answer
> 2 votes
How about OpenGL 2.0/2.1? It would cover machines up to 2008/2010 that are running Intel processor with Integrated Graphics and I really think it would be sufficient.

Unless you already know exact end user group and you know that they have hardware from before that time (like in some poorer regions of the world). But OpenGL is still a way to go if you need long-term, cross-platform capabilities. OpenGL 1.4 would cover machines approximately up to 2004 (again, with Intel IG).

To make use of newer users hardware, you could if-else or #ifdef your code and make it running shaders and all those recent goodies if HW supports it. For older HW you would roll back to old, fixed-function pipeline and display less-satisfactory graphics.

Running 3.x+ OpenGL with compatibility profile might be way to go, as it allows usage of old functions.

List of Intel GPUs with API versions they support: LINK

Correlation table of OpenGL and GLSL versions: LINK

# Answer
> 1 votes
No. Forget about those who don't upgrade their setups in years. It's just dumb to drastically reduce product quality in favor of them (Because your game's availability is not your game's desirability). Better stick with modern OpenGL and focus on developing a good game. Later you could backport it, if older hardware would be enough to and if you will still want to.

---
Tags: opengl, 3d, compatibility
---


# Question
Title: Problem in multiplayer game lobby trying to pass map name to MasterServer.RegisterHost
I'm working on an online multiplayer game, so I have lobby where users can see the hosts list. Every host in the hosts list has some information like "host user name" and "map name".

I'm using this code to register the host and load "host user name":

```
public void something()
{
    var useNet = !Network.HavePublicAddress ();
    Network.InitializeServer (6, 25000, useNet);
    MasterServer.RegisterHost ("roomname", hostUserName , "unity");
}

public void btn_Refresh()
{
    MasterServer.RequestHostList ("roomname");
    data = MasterServer.PollHostList ();

    for (int i=0; i<data.Length; i++)
    {
        ButtonRoom [i].gameObject.SetActive(true);
        TextNameRoom [i].text = data [i].gameName;
    }
}

```

I also need "map name", exactly like "host user name", so I added another value to `MasterServer.RegisterHost()` like this:

```
public void something()
{
    var useNet = !Network.HavePublicAddress ();
    Network.InitializeServer (6, 25000, useNet);
    MasterServer.RegisterHost ("roomname", hostUserName, mapName, "unity");
}

```

but now I have an error that `RegisterHost()` can't have 4 arguments:

> No overload for method `RegisterHost` takes `4` arguments

What other way could I pass the map name? Thank you.

# Answer
> 1 votes
In the above scenario, you are using `MasterServer.Register(string gameTypeName, string gameName, string comment = "")`. While you do not need to provide the third `string`, for the comment, you can not pass in a fourth `string`, as the function is not overloaded to take it.

If you really wish to pass the map name in with this function, one option would be to simply append it to your comment. You can then handle the comment as a 'set' of parameters, which can be split up on the other end in several ways.

## Combining the string, and working with known character count

Consider the following map options:

```
public enum Maps{
                  killzone,        // 8 characters
                  killzone alpha,  // 14 characters
                  dusk,            // 4 characters
                  daylight         // 8 characters
                }

```

You can append a map name to the comment, by calling the function as follows:

```
MasterServer.Register("roomname", hostUsername, mapName + "unity");

```

Note that in this example, it is important you append the `mapName` to the *start* of the comment. If you wish to add additional string parameters in this way, scroll down to ***Combining the string with a deliberate separator***, as that approach would be more suitable.

On the other side, when you first handle your `comment`, you can look at the first letter(s) to work out the map. Remember, since a `string` is effectively a character array, we look at the first character with `string[0]`.

```
map mapName;

switch(comment[0])
{
    case 'd':  // dusk, daylight
        if(comment.StartsWith("dusk"))
        {
            mapName = Maps.dusk;   // we are using the "dusk" map
            comment.Remove(0, 4);  // remove 4 characters from the start of comment
        }
        else if(comment.StartsWith("daylight"))
        {
            mapName = Maps.daylight;   // we are using the "daylight" map
            comment.Remove(0, 8);      // remove 8 characters from the start of comment
        }
        else
        {
            // Throw error; unidentified map
        }

        break;
    case 'k': // killzone, killzone alpha
        if(comment.StartsWith("killzone"))
        {
            if(comment.StartsWith("killzone alpha")
            {
                mapName = Maps.killzone alpha;   // we are using the "killzone alpha" map
                comment.Remove(0, 14);     // remove 14 characters from the start of comment
            }
            else
            {
                mapName = Maps.killzone;   // we are using the "killzone" map
                comment.Remove(0, 8);      // remove 8 characters from the start of comment
            }

        }
        else if(comment.StartsWith("daylight"))
        {
            mapName = Maps.daylight;       // we are using the "daylight" map
            comment.Remove(0, 8);          // remove 8 characters from the start of comment
        }
        else
        {
            // Throw error; unidentified map
        }

        break;
    default:
        // Throw error; unidentified map
}

```

In the above example, I use a `switch` statement on the first character to narrow down the options. If the first character does not match any possible option, I immediately throw an error. This is a good idea to have as a default, whenever checking the strings, as you can easily make a mistake - whether it be spelling, capitalisation or something else that seems trivial.

From there, I use a `String.StartsWith(string)` to confirm that the start actually matches a possible map name. *It is always a good idea to double check these things, but obviously the maps will be hard coded. It may not be necessary to be this safe*. Another option you have is to check the second and third characters with `comment[1]` and `comment[2]`, to further narrow down the possible map options with a single character check, rather than an entire string check. For another example, after confirming that `comment[0] == 'k'`, you might consider checking that `comment[8] == ' '`, or that `comment[9] == 'a'`, to work out if you are using `killzone` or `killzone alpha`.

Lastly, I make sure to remove the characters from the start of the string, with `String.Remove(int, int)`. This is why I include the commented character size in the `enum Maps`. Always user a `startIndex` of `0`, and be careful you do not eat in to the rest of your `comment` by passing the wrong `count`.

**There is one important thing to consider:** If you have a `mapName` of `killzone`, and for some reason have an original `comment` of `" alphalpha"`, the combined comment of `"killzone alphalpha"` would falsely trigger the `Maps.killzone alpha` map, and leave you with a `comment` of `"lpha"`. This may not be an issue, if you do not give user control over the actual comment, but if you do this could lead to an undesirable bug. It still might be a better idea to consider the second option, directly below.

## Combining the string with a deliberate separator

You could also append the map name using a unique separator character, like so:

```
MasterServer.Register("roomname", hostname, (mapname + '-' + "unity");

```

Note that in the example, I have deliberately separated the `'-'` from `"unity"`. You can use any character to seperate the strings, but you must ensure that that character is not used in the strings, so we do not accidentally break the string up further than we intend.

When we mean to interpret the string on the other end, we can simply split it up into its sections, with `String.split(char)`.

```
string[2] parameters = comment.Split('-');

```

This gives us two seperate strings. `string[0]` would contain the `mapname`, while `string[1]` would contain `"unity"`. In this way, you could load in additional parameters.

You just have to ensure that as well as using a *unique* separator character, you also interpret the split strings correctly on the other end. For instance, ensure that you keep note of what order you send the above string in as, so you do not interpret `"unity"` as a map name. Also ensure that you handle the split up version for displaying your comment, as the `comment` variable will still contain the combined string values you originally sent in.

This gives the result you intend in the above code, where you achieve a fourth string containing the map name.

---
Tags: unity, multiplayer
---


# Question
Title: How do I accuratley switch lanes with my script?
Hi I'm working on a 3 lane 3d endless runner game and I came across this issue. With some help from this stack overflow, I managed to switch my character in the 3 lane, after couple of seconds my character slowly moves away from the lanes, simply rather than running a straight line on each lane, After switching the character moves away from the lane. It is really annoying. How do I fixed it? I came to notice that the character's x axis, the point values increases littlie by little. for e.g. If it is the right lane it should be 1.0000, but after switching it increases gradually 1.0045, 1.0345, 1.09585 so on and vise versa too. Also sometimes it also breaks the 3 lane movement and the character tries to move all the way to the right or left without stopping, so I have to stop play mode.

Help would be greatly appreciated.

Here's my script.

```
 //Variables for Lane switching
    private bool isChangingLane = false;
    private Vector3 locationAfterChanginLane = Vector3.zero;
    private Vector3 sideWayMovementDistance = Vector3.right * 2f; // This might be the case that triggers abnormal movements
    private float sideWaySpeed = 6f;

    public enum Lane
    {
        Left,
        Right,
        Center
    }

    public enum MoveDirection
    {
        Left,
        Right,
        None
    }

    Lane currentLane = Lane.Center;

     void Update()
    {
        currentBaseState = anim.GetCurrentAnimatorStateInfo(0);

        if (controller.isGrounded)
        {
            verticalVelocity = -0.5f;
            if (currentBaseState.fullPathHash == locoState)
            {
                if (Input.GetButtonDown("Jump"))
                {
                    verticalVelocity = 18f;

                    anim.SetBool("Jump", true);
                }
                else if (Input.GetKeyDown(KeyCode.S))
                {
                    anim.SetBool("Slide", true);
                }

            }

            MoveLeftRight(); // This is the method to move right and left.

            if (isChangingLane)
            {
                if (Math.Abs(transform.position.x - locationAfterChanginLane.x) < 0.1f)
                {
                    isChangingLane = false;
                    moveVector.x = 0;
                }
            }

        }
    }

    private void MoveLeftRight()
    {

        MoveDirection requestedMoveDirection = MoveDirection.None;
        if (Input.GetKeyDown(KeyCode.A) && !isChangingLane)
        {
            requestedMoveDirection = MoveDirection.Left;
            isChangingLane = true;
        }
        else if (Input.GetKeyDown(KeyCode.D) && !isChangingLane)
        {
            requestedMoveDirection = MoveDirection.Right;
            isChangingLane = true;
        }

        switch (requestedMoveDirection)
        {
            case MoveDirection.Right:
                if (currentLane == Lane.Right)
                {
                    Debug.Log("Right Lane");
                    break; //Do nothing when in right lane.

                }
                else if (currentLane == Lane.Center)
                {
                    locationAfterChanginLane = transform.position + sideWayMovementDistance;
                    moveVector.x = +sideWaySpeed;

                    currentLane = Lane.Right;
                    Debug.Log("Center --> Right");
                }
                else if (currentLane == Lane.Left)
                {
                    locationAfterChanginLane = transform.position + sideWayMovementDistance;
                    moveVector.x = +sideWaySpeed;

                    currentLane = Lane.Center;
                    Debug.Log("Left --> Center");
                }
                break;
            case MoveDirection.Left:
                if (currentLane == Lane.Left)
                {
                    Debug.Log("Left Lane");
                    break; //Do nothing when in left lane.
                }
                else if (currentLane == Lane.Center)
                {
                    locationAfterChanginLane = transform.position - sideWayMovementDistance;
                    moveVector.x = -sideWaySpeed;

                    currentLane = Lane.Left;

                    Debug.Log("Center --> Left");
                }
                else if (currentLane == Lane.Right)
                {
                    locationAfterChanginLane = transform.position - sideWayMovementDistance;
                    moveVector.x = -sideWaySpeed;

                    currentLane = Lane.Center;

                    Debug.Log("Right --> Center");
                }
                break;
        }
    }

```

# Answer
> 2 votes
I would suggest setting a `Clamp`. I created my own for some lighting effects like this:

```
public static float Clamp(float val, float min, float max)
{
    return (val < min) ? min : (val > max) ? max : val;
}

```

You can then change a global variable for min/max, maybe just setting them both to a static value. This can be run during update to constantly keep the float from sliding out of where you want it to be. You could also use this with a slight variation of min/max to allow a slight swaying movement as your player runs, which could look pretty awesome depending on the rest of the game.

In this case, `val` is whatever the current value is. So you might switch to a planar value (the one that your player sways from now), then `Clamp` to +/- 0.01 of that value. So let's say you want your `x` value to be `1.25f`. You move the character to `1.25f` and then `Clamp` against that in your update with something like:

```
 leftLaneMin = 1.24f;
 leftLaneMax = 1.26f;
 centerLaneMin = 2.49f;
 centerLaneMax = 2.51f;
 rightLaneMin = 3.74f;
 rightLaneMax = 3.76f;

 laneValue = leftLaneMin;
 player.x = (laneValue, leftLaneMin, leftLaneMax);

```

That would keep player.x "stick" between 1.24f and 1.26f.

# Answer
> -2 votes
If your character is still moving after it changes lanes. You might want to set a variable of boolean to lock that specific axis while he's running. I am thinking it is moving because of the physics on the engine.

You can lock an axis in the editor. Or you can do it also on the script.

https://docs.unity3d.com/ScriptReference/Rigidbody-constraints.html https://docs.unity3d.com/ScriptReference/RigidbodyConstraints.FreezePositionX.html

---
Tags: unity, movement
---


# Question
Title: Instantiate the same gameobject multiple times at once
So i am trying to create code where by when I shoot, bullets will shoot out of my gun at the same time, from 3 different positions. If I do a singular instantiate, it works fine, like below:

```
   IEnumerator ShotgunCoolDown()
    {
        PistolGunEffect.SetActive(false);
        canShoot = true;
        yield return new WaitForSeconds(0.45f);
        GetComponent<AudioSource>().PlayOneShot(PistolGunSound);
        canShoot = false;
        StartCoroutine(COPlayOneShot("Fire"));
        RifleGunEffect.GetComponent<ParticleSystem>().Play();
        (Instantiate(PistolBullet, ShotgunPoint.transform.position, transform.root.rotation) as GameObject).GetComponent<BulletScript>().Activate();
        yield return new WaitForSeconds(0.25f);
    }

```

However if i add multiple instantiates with different positionings, it will spawn the bullet for a millisecond before disappearing:

```
     IEnumerator ShotgunCoolDown()
        {
            PistolGunEffect.SetActive(false);
            canShoot = true;
            yield return new WaitForSeconds(0.45f);
            GetComponent<AudioSource>().PlayOneShot(PistolGunSound);
            canShoot = false;
            StartCoroutine(COPlayOneShot("Fire"));
            RifleGunEffect.GetComponent<ParticleSystem>().Play();
            (Instantiate(PistolBullet, ShotgunPoint.transform.position, transform.root.rotation) as GameObject).GetComponent<BulletScript>().Activate();
            (Instantiate(PistolBullet, ShotgunPoint1.transform.position, transform.root.rotation) as GameObject).GetComponent<BulletScript>().Activate();
            (Instantiate(PistolBullet, ShotgunPoint2.transform.position, transform.root.rotation) as GameObject).GetComponent<BulletScript>().Activate();
yield return new WaitForSeconds(0.25f);
 }

```

Any ideas how to address this?

# Answer
> 0 votes
It is most probably a problem regarding your bullets being able to collide with bullets. (as noted by the various comments) To solve this, go to Edit -\> Project -\> Physcis in Unity's menu in the upper left corner. You will see a Layer Collision Matrix. Checking/unchecking boxes enables you to tell the engine which layer can collide with which.

If you have no 'Bullet' layer, create one and then set it up as you wish.

---
Tags: c#, unity
---