user237948
user237948

Reputation: 121

Move character in unity

I am new to unity and was wandering how to move a character so that it will stop when it hits a wall.

Currently i have used code like this:

Vector3 pos = transform.position;
if(Input.GetKey("a")) pos.x -= 1;
if(Input.GetKey("d")) pos.x += 1;
transform.position = pos;

However with this the character will move through walls. I have added a rigidbody component to the char.

EDIT: Yes they do have a box collider on them, and the char does actually start to "bounce" when they collide, but the char goes right through the wall.

Upvotes: 0

Views: 1611

Answers (1)

You need to let the Physics engine do the moving for you, so don't set the transform.position yourself. Set the rigidbody.velocity instead.

int xVelocity = 0;
if(Input.GetKey("a"))
{
    xVelocity = -1;
}
else if(Input.GetKey("d"))
{
    xVelocity = 1;
}

rigidbody.velocity = new Vector3(xVelocity, 0, 0);

Upvotes: 1

Related Questions