- Home /
My object can't move left and right but only jump?
I can only make my object jump, but not move left and right? I can't see why my code wouldn't work.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
public CharacterController controller;
private float gravity = 12.04f;
private float jumpForce = 6f;
private float verticalVelocity;
public float speed;
public Rigidbody rb;
void Start () {
rb = GetComponent<Rigidbody> ();
controller = GetComponent<CharacterController> ();
}
void FixedUpdate(){
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, moveVertical, 0.0f);
rb.AddForce (movement * speed);
}
private void Update(){
if (controller.isGrounded) {
verticalVelocity = -gravity * Time.deltaTime;
if (Input.GetKeyDown (KeyCode.Space)) {
verticalVelocity = jumpForce;
}
} else {
verticalVelocity -= gravity * Time.deltaTime;
}
Vector3 moveVector = Vector3.zero;
moveVector.y = verticalVelocity;
controller.Move (moveVector * Time.deltaTime);
}
}
Answer by Ark_Revan · May 19, 2017 at 02:00 PM
Vector3 movement = new Vector3 (moveHorizontal, moveVertical, 0.0f);
This line does this : I move forward ( X ) by my moveHorizontal value. I move up/down ( Y ) by my moveVertical value. I move right/left( Z ) by 0.0f.
Try to put moveHorizontal instead of 0.0f, you should start moving in up/right or back/left. If it works, then it means you need to get the correct input instead of 0.0f. If you still can't move in any other direction , then the problem is elsewhere.
Your answer
Follow this Question
Related Questions
How to make rigidbody.AddForce and controller.Move work together? 0 Answers
Face forward direction of movement 3 Answers
Applying force to my object has no effect. 1 Answer
adding force 1 Answer