- Home /
Movement Code not working
Hi guys I have a code that doesn't seem to be working for 3D I can move left and right but i cannot go forwards or backwards and my jumping is perfectly fine for my purpose. I would like you guys to look at the below script and let me know.
using UnityEngine;
using System.Collections;
public class PlayerMove: MonoBehaviour {
public float speed = 5f;
public float jumpSpeed = 8f;
private float movement = 0f;
private Rigidbody rigidBody;
private float move = 0f;
// Use this for initialization
void Start () {
rigidBody = GetComponent<Rigidbody> ();
}
// Update is called once per frame
void Update () {
movement = Input.GetAxis ("Horizontal");
move = Input.GetAxis ("Vertical");
if (movement > 0f) {
rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
}
else if (movement < 0f) {
rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
}
if (move > 0f) {
rigidBody.velocity = new Vector2 (move * speed, rigidBody.velocity.z);
}
else if (move < 0f) {
rigidBody.velocity = new Vector2 (move * speed, rigidBody.velocity.z);
}
if(Input.GetButtonDown ("Jump")){
rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
}
}
}
Answer by Raimi · Jul 04, 2017 at 12:46 PM
Not Quite sure. You are using a Vector2 to move along Z axis. Vector2 takes X and Y. You should use Vector3 which takes X, Y and Z.
Answer by cbjunior · Jul 04, 2017 at 01:01 PM
You're using Vector2s, which only define the dimensions x and y, which in Unity 3D space represent left/right and up/down respectively.
You should use a Vector3 to represent the velocity in three dimensional space, it will be more intuitive and account for all three dimensions of movement.
Vector3 movement = Vector3.zero;
void Update()
{
movement = new Vector3 (InputGetAxis ("Horizontal"), 0.0f, Input.GetAxis ("Vertical"));
rigidbody.velocity = movement * speed;
}
EDIT: After reading through your code again, I don't think you exactly understand what vectors are. Vectors represent a point in space or a direction, depending on how you use them. They don't associate one value with another, which is how you seem to be using them. I would recommend reading through some of the tutorials to get a better grasp on Vectors.
I didn't post an entire script. I was just showing them how to use a Vector3 to define three dimensional movement.