- Home /
Movement restriction...
I have a 2D sprite that I can move right and left with transform.translate
. However, this is very inefficcient and I dislike it. I thought of using SimpleMove but then again, all I needed was movement right and left between the (-5) to (5) positions on the X axis.
Can I possibly continue the use of transform.translate
, but instead have a special restriction that ignores movement when reaching the specific positions?
Thanks in advance! :D
Comment
Best Answer
Answer by Aridez · Feb 17, 2014 at 03:48 PM
If you want your sprite to move left and right you could attach a rigidbody2D to it and then use the rigidbody2D.velocity to move left and right:
void FixedUpdate {
float move = Input.GetAxis ("Horizontal");
rigidbody2D.velocity = new Vector2 (move * speed, rigidbody2D.velocity.y);
}
Then to restrict the movement you could use a function like:
if (transform.position.x > 5)
transform.position = new vector2(5, transform.position.y); // can't go further than 5
else if (transform.position.x < -5)
transform.position = new vector2(-5, transform.position.y); // can't go further than -5
I'm not sure if this will help but hope it does!