- Home /
Why isn't my player moving?
using UnityEngine;
using System.Collections;
public class Monkey : MonoBehaviour {
public float speed = 5f;
public float movement = 0f;
private Rigidbody2D rigidBody;
// Use this for initialization
void Start () {
rigidBody = GetComponent<Rigidbody2D> ();
}
// Update is called once per frame
void Update() {
movement = Input.GetAxis ("Horizontal");
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);
}
else {
rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
}
}
}
What do you mean by not moving? Are you just pressing left and right and it won't do anything?
Also, just so you know, when the left key is pressed it will also move right. Change line 22 to: rigidBody.velocity = new Vector2 (-movement * speed, rigidBody.velocity.y);
Well, i guess that the problem is with the movement
because it is equals 0. so no matter what you do, the change on the Y axis will always be zero.
Okay, can you start by explaining your game and what exactly are you trying to do?
Answer by PersianKiller · Sep 16, 2017 at 05:37 AM
change public float speed = 5f; to public float speed ; then go to unity editor and change the value of speed inside the unity via inspector , or you should use private float speed=5f;
also you can use this it's a little smaller.
public Rigidbody2D rigidBody;
public float mooooove;
public float moveSpeed;
void Start () {
rigidBody = GetComponent<Rigidbody2D> ();
}
void Update () {
mooooove = Input.GetAxisRaw ("Horizontal");
if (mooooove != 0) {
rigidBody.velocity = new Vector2 (mooooove*moveSpeed,rigidBody.velocity.y);
transform.localScale = new Vector3 (mooooove,1,1);
}
if (mooooove == 0) {
rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
}
I used the code, but it only makes my player rotate left and right and not make it move :(
dude your code was fine just change public float speed = 5f; to private float speed = 5f;
Your answer
Follow this Question
Related Questions
Box Collider 2d don't collide 3 Answers
rigidbody2d does not follow physical rules 0 Answers
Stop Rigidbody2D from overlapping 0 Answers
2018.2.17 OnTriggerEnter2D not working 1 Answer
How to stop Rigidbody2D from getting stuck on corners? 1 Answer