I am trying to make a gameobject in Unity 4.6 move left and right. Basically, the gameobject, when pressed the key, d, moves forward on the x axis until w is released and again when the a key is pressed the gameobject moves backwards on the x axis.
Without physics2D?
if(Input.GetKey(KeyCode.A))
{
transform.position += transform.right * -speed * Time.deltaTime;
}
With physics2D?
add a rigidbody2D to the object, then try the following (I have all movements here because this is from a small 2D test I was doing). This will work with 2D physics so your object can’t pass through other 2D colliders.
Vector2 movement = Vector2.zero;
if(Input.GetKey(KeyCode.A))
{
movement.x = (transform.right*Time.deltaTime*-moveSpeed).x;
}
if(Input.GetKey(KeyCode.D))
{
movement.x = (transform.right*Time.deltaTime*moveSpeed).x;
}
if(Input.GetKey(KeyCode.W))
{
movement.y = (transform.up*Time.deltaTime*moveSpeed).y;
}
if(Input.GetKey(KeyCode.S))
{
movement.y = (transform.up*Time.deltaTime*-moveSpeed).y;
}
movement = movement + (Vector2)(transform.position);
rigidbody2D.MovePosition(movement);
Alright, I used the code with physics2D and these two errors appeared: (1,9) : error CS0116: A namespace can only contain types and namespace declarations and (3,2): error CS8025: Parsing error. I would normally try to fix them myself, however, I do not know much C#.
That second one came straight out of a working example I’m going to teach a class on Tuesday, haha. I hope it’s not a javascript error, most of that class if not all are using javascript…
The first error sounds like you’ve got one extra bracket somewhere in your code. If you put this code in your Update function on an object that has a rigidbody2D, it should run fine. The second error has the same cause. Both CS0116 and CS8025 errors can be fixed if you check your brackets and make sure they all close. Every opening { needs a closing }. If you can’t find the error, try posting the code here.