How do I move a game object only on the x axis with arrow keys?
I am new to Unity and trying to make a space invaders game . I don't know how to move a game object with just arrow keys only on the x axis. I prefer to code in C# but JS would be fine.
Answer by NinjaISV · Nov 18, 2015 at 01:52 AM
I'm assuming you're making a 2D game because you only want the object to move on the x axis, so the first thing you'll need to do is add a Rigidbody2D to the object you're planning on moving. Next set it's "Gravity Scale" to 0 and constrain its angle on the z axis so it doesn't spin around randomly. Now just make a class with this code in it and attach it to the object you would like to move around. You can also change how fast it moves by modifying the "Speed' variable in the inspector.
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float speed = 3f;
Rigidbody2D rigidbody2d;
void Awake () {
rigidbody2d = GetComponent<Rigidbody2D> ();
}
void FixedUpdate () {
if (Input.GetKey (KeyCode.LeftArrow))
rigidbody2d.velocity = new Vector2 (speed * -1, 0f);
if (Input.GetKey (KeyCode.RightArrow))
rigidbody2d.velocity = new Vector2 (speed, 0f);
}
}
All this code is doing is getting the Rigidbody2D at the very beginning then assigning its velocity when the player presses the left and right keys.