Search code examples
c#unity-game-engine

How can I fix my movement code? The player won't move correctly


I am new to coding and c#, but I have been trying to make my player without gravity affecting it. But my player keeps moving up and doing nothing else. I have started by trying to make it move to the left and right. I am not sure where I went wrong or if I should start over as I am not to far in or if I should fix a small mistake.

Here is my code:

     using System.Collections;
     using System.Collections.Generic;
     using UnityEngine;

     public class PlayerMovement1 : MonoBehaviour
     {
     private float speed;
     // Start is called before the first frame update
     void Start()
     {
        
     }

     // Update is called once per frame
     void Update()
     {
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");

        Vector2 direction = new Vector2(horizontalInput, verticalInput);

        transform.Translate(direction * speed * Time.deltaTime);
     }
     }

Solution

  • you are transferring the object that PlayerMovement1 script is attached. how is a gravity affecting your object? with rigidbody? if you have a gravity with rigidbody, the "translate" doesn't care it and move anyway but it doesn't recommended for most cases because in this way the object can't detect the collisions and if you have rigidbody at the same time, you get weird movements and shakings. you should move your object with the rigidbody instead of transferring your object with transform. To do this; you should get the rigidbody from the inspector menu. write that code and assign the rigidbody:

    [SerialiseField] Rigidbody2D rigidbody;
    

    now you can assign the rigidbody. Just change your rigidbody's velocity and move the object in the update method (FixedUpdate for better movement but be careful because it can't detect the "input.getkey" methods everytime):

    float horizontalInput = Input.GetAxis("Horizontal");
    float verticalInput = Input.GetAxis("Vertical");
    
    Vector2 direction = new Vector2(horizontalInput, verticalInput);
    rigidbody.velocity = direction * speed;
    

    Lastly, don't forget to disable the gravity at the start method(as I understand from your message you want to do it):

    rigidbody.gravityScale = 0;
    

    Also, is your game 2d or 3d?