1

I have been trying to make a movement script for my player in a 2D game but without success. I do not know why it is not working.

The problem is that the player isn't moving. I have a RigidBody attached and gravity on. (Not sure if gravity makes such a difference but I just thought to mention it.)

using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {
   public Rigidbody rb;
   public float speed = 10;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void FixedUpdate () {
    float mx = Input.GetAxisRaw("Horizontal");
    float mz = Input.GetAxisRaw("Vertical");

    Vector3 movement = new Vector3(mx, 0.0f, mz);
    Debug.Log(movement);
    rb.AddForce(movement * speed * Time.deltaTime);

  }
}
4
  • As a curiosity, what does the Debug log show for movement when you adjust the axis? My hunch is that you are adding a force which is not enough to move the object. Checking your movement, speed, and Time.deltaTime variables for proper values would be my first thought. Commented Oct 1, 2015 at 21:40
  • My thoughts are the same as Kivak Wolf's. Keep in mind that Time.deltaTime is generally a really small number (1/60-ish). Since speed is 10 and the component values of movement only vary between -1 and 1, the final force you add is going to be quite small. Might not be enough to visually overcome the inertia of an object, let alone friction. Commented Oct 1, 2015 at 21:50
  • Thank you all for such quick responses. Awesome community. It started working when I changed the speed value. Commented Oct 2, 2015 at 4:15
  • The debug.log for the variable movement just logs the vector and I was checking if it was getting any input or not. It shows a vector with x,y,z in the console. The values can either be 0, 1 or -1. Thanks again for reading. :) Commented Oct 2, 2015 at 4:17

1 Answer 1

3

You may wanna make sure you are adding enough force to actually cause the player to move. Try increasing the force variable incrementally until you see a change. Hope this helps!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. It worked. Dont know why I didn't try that earlier. Hope you have an awesome day :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.