FOR BEGINNERS: simple movement script c# (no jump)

{
public float movementSpeed;

// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void FixedUpdate()
{
if(Input.GetKey(KeyCode.LeftShift) && Input.GetKey(“w”)) {
transform.position += transform.TransformDirection(Vector3.forward) * Time.deltaTime * movementSpeed * 2.5f;
} else if(Input.GetKey(“w”) && !Input.GetKey(KeyCode.LeftShift)) {
transform.position += transform.TransformDirection(Vector3.forward) * Time.deltaTime * movementSpeed;
} else if (Input.GetKey(“s”)) {
transform.position -= transform.TransformDirection(Vector3.forward) * Time.deltaTime * movementSpeed;
}

if(Input.GetKey(“a”) && !Input.GetKey(“d”)) {
transform.position += transform.TransformDirection(Vector3.left) * Time.deltaTime * movementSpeed;
} else if (Input.GetKey (“d”) && !Input.GetKey(“a”)) {
transform.position -= transform.TransformDirection(Vector3.left) * Time.deltaTime * movementSpeed;
}

}
}

What’s your intent?

Do you just want to share code (the title suggests it, kind of…).

You should generally include some descriptions of what you’re posting… even if you just want to share code.
However, sharing code in a forum just for fun is not a thing here, there are other places to do that.

In the future, please use code tags. Also, please be aware that the code needs basic improvements.

If you were to ask for help, include more information, please.

1 Like

This is a pretty roundabout way to create basic movement, to be honest.
For one thing, you don’t want to check for user-input in FixedUpdate , and FixedUpdate isn’t necessary here since you’re not moving the GameObject using a Rigidbody/Rigidbody2D.

All of this could be condensed down to:

public class PlayerMover : MonoBehaviour {
   public float moveSpeed;
   public float sprintSpeed;

   void Update() {
      //Assuming this is 3rd-person movement and the default Input Manager configuration is used.
      Vector3 moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));

      //Use the value of "sprintSpeed" if left-shift is held down, otherwise use the value of "moveSpeed";
      float speed = Input.GetKey(KeyCode.LeftShift) ? sprintSpeed : moveSpeed;

      //Update the GameObject's position with the detected move direction and speed.
      transform.position += moveDirection * speed * Time.deltaTime;
   }
}

Regardless though, this may soon be obsolete with Unity’s new input system.

I think he just wants to help beginners judging from the title ‘FOR BEGINNERS: simple movement script c#’
.

It’s also an old post so really doesn’t need necroing TBH.

1 Like