Reputation: 11
I want to limit the movement along both the X and Y axis between -7.5 and 7.5. What is the simplest way to achieve this?
Here is my movement script so far:
using UnityEngine;
using System.Collections;
public class PlayerPaddle : MonoBehaviour {
private float speed = 0.1f;
void Start ()
{
}
void Update ()
{
if (Input.GetKey(KeyCode.UpArrow))
this.transform.position += Vector3.up * speed;
if (Input.GetKey(KeyCode.DownArrow))
this.transform.position += Vector3.down * speed;
if (Input.GetKey(KeyCode.LeftArrow))
this.transform.position += Vector3.left * speed;
if (Input.GetKey(KeyCode.RightArrow))
this.transform.position += Vector3.right * speed;
}
}
Upvotes: 0
Views: 306
Reputation: 1863
You're going to ensure that the current position PLUS the next move does not go outside your boundary.
You may want to look up some literature on collision detection. Here is an example:
Example:
if (Input.GetKey(KeyCode.LeftArrow))
{
if((this.transform.position + (Vector3.left * speed)) > -7.5)
this.transform.position += Vector3.left * speed;
}
Upvotes: 1