Limiting the movement of a player object moved by transform.translate (Unity 5)
Hi! I'm completely new to Unity and I am trying to limit the movement of my object.
I am using transform.translate to move my player object and so far it's working great. But I would want to limit its movement to -8 and 8 in the x-axis so that it won't go out of the bounds.
Here is my code:
public float mspeed = 10f;
private Vector3 movement = new Vector3 (5f, 0f, 0f);
void Start()
{
}
void Update ()
{
PlayerController ();
}
void PlayerController()
{
if (Input.GetKey(KeyCode.D))
{
transform.Translate (movement * mspeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.A))
{
transform.Translate (-movement * mspeed * Time.deltaTime);
}
}
I heard it's possible thru mathf.clamp but i don't know how to implement it on a transform.translate so I'm basically lost.
$$anonymous$$athf.Clamp works with one float or int. Transform.position is a Vector3, which consists of three floats. Thus, you just need to use Clamp after transform.Translate to limit the x value of the transform.position Vector3.
transform.Translate (movement * mspeed * Time.deltaTime);
transform.position = new Vector3($$anonymous$$athf.Clamp(transform.position.x, -8, 8), transform.position.y, transform.position.z);
or
transform.Translate (movement * mspeed * Time.deltaTime);
Vector3 pos = transform.position;
pos.x = $$anonymous$$athf.Clamp(pos .x, -8, 8);
transform.position = pos;
The Scripting API has this exact example.
Your answer
Follow this Question
Related Questions
How to ignore rotation while moving? 2 Answers
How can I move an object between two positions, while it is on a rotating platform? 0 Answers
Limit movement to just forward/backward and left/right 0 Answers
How can I make sprite stay in viewport and point towards the game object it is attached to? 1 Answer
Set limit to transform.translate 2 Answers