Reputation: 81
I was wondering if anyone has any idea how to go about doing this in c# (Unity). Whenever the left or right arrow is pressed the player will move a certain amount left / right on the x axis, and can't move when they are next to the game border.
Thanks!
Upvotes: 0
Views: 2385
Reputation: 3040
As far as the movement goes there are a couple of ways you could handle this. If you do not care about your object interacting with the physics system, the simplest way to move an object is by using transform.Translate
like this:
void Update ()
{
if(Input.GetKey(KeyCode.LeftArrow))
{
transform.Translate(-Vector3.right * Time.deltaTime);
}
else if(Input.GetKey(KeyCode.RightArrow))
{
transform.Translate(Vector3.right * Time.deltaTime);
}
}
If by "moving the gameObject on the x axis a certain amount" you mean that you want the object to move a certain distance instantaneously when a key is pressed, you can do so by using the GetKeyDown
function and multiplying your Vector3 by a distance factor like so:
int distance = 2;
void Update ()
{
if(Input.GetKeyDown(KeyCode.LeftArrow))
{
transform.Translate(-Vector3.right * distance);
}
else if(Input.GetKeyDown(KeyCode.RightArrow))
{
transform.Translate(Vector3.right * distance);
}
}
In order to keep an object within a certain range of positions, use the Mathf.clamp
function. This method takes three parameters: the value you want to clamp, the minimum the value is allowed to be, and the maximum a value is allowed to be.
So for example, if using the above code you wanted to restrict the movement of your object to all X values between -1 and 1, you would add the following code snippet at the end of your update.
Vector3 pos = transform.position;
pos.x = Mathf.Clamp (pos.x, -1, 1);
transform.position = pos;
This will clamp the gameobject's x position such that is stays between -1 and 1.
Edit:
Additionally, to handle movement you can take advantage of the unity input manager which already has some good defaults set up for you. For example, to handle left and right movement using the arrow keys, you can take advantage of Input.GetAxis("Horizontal")
. The advantage to this is that the "Horizontal" axis is mapped to the left and right arrow keys, as well as A and D on the keyboard. This means your game can easily function using several common control types and you don't have to hard code your control scheme.
If you want to control the speed your object moves, you can multiply your movement Vector3 by a speed factor. Here is an example which achieves the same result as above, but uses Input.GetAxis
and a speed factor to control movement speed:
public float Speed = 2f;
void Update ()
{
Vector3 moveDirection = new Vector3 (Input.GetAxis ("Horizontal"), 0, 0);
moveDirection *= Speed;
moveDirection *= Time.deltaTime;
transform.Translate (moveDirection);
Vector3 pos = transform.position;
pos.x = Mathf.Clamp (pos.x, -1, 1);
transform.position = pos;
}
Upvotes: 1