Character moving itself [SOLVED]

I’m doing endless runner in Unity and my player is for some reason moving to the left without me pressing anything.

Here is the code that I’m using:

using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerMovement : MonoBehaviour
{
    bool alive = true;

    public float speed = 5;
    public Rigidbody rb;

    float horizontalInput;
    public float horizontalMultiplier = 2;

    void FixedUpdate()
    {
        if (!alive) return;

        Vector3 forwardMove = transform.forward * speed * Time.fixedDeltaTime;
        Vector3 horizontalMove = transform.right * horizontalInput * speed * Time.fixedDeltaTime * horizontalMultiplier;
        rb.MovePosition(rb.position + forwardMove + horizontalMove);
    }
    void Update()
    {
        horizontalInput = Input.GetAxis("Horizontal");

        if(transform.position.y < -5)
        {
            Die();
        }
    }

    public void Die()
    {
        alive = false;
        Invoke("Restart", 1);
    }

    void Restart()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}

And here is screenshot of the player:


Can someone please help me?

Your FixedUpdate keeps adding a non-zero vector to position, unconditional to any user input.

And how can I fix it?

Since you’re moving the rigidbody with MovePosition, I assume it doesn’t react to collisions, right?
You can then check Is Kinematic in rigidbody properties, so it won’t ever move to the side. If it still does, there is something wrong with the transform, either the road you’re running on is rotated or your player is.

My player was rotated the whole time to 88 instead of 90…
Thanks a lot for the help.

1 Like