Home > Back-end >  Player Sprite Doesn't Move (Unity, C#)
Player Sprite Doesn't Move (Unity, C#)

Time:08-03

I was attempting to make a top down 2D shooter using Unity. My code contains no errors that I could see, RigidBody2D and PlayerMovement (code for the player to move) have been added to the sprite, and RigidBody2D has been added to the PlayerMovement. My move speed is set to 5. Please let me know what I can do to fix this issue!

Code:

using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour 
{
    public float moveSpeed;
    public Rigidbody2D rb;
    Vector2 movement;

    void Update()
    {
        MovementInput();
    }

    private void FixedUpdate()
    {
        rb.velocity = movement * moveSpeed;
    }
    
    void MovementInput()
    {
        float mx = Input.GetAxisRaw("Horizontal");
        float my = Input.GetAxisRaw("Vertical");
        
        movement = new Vector2(mx, my).normalized;
    }
}

CodePudding user response:

First try putting MovementInput() into FixedUpdate before the rb.velocity line. Please inform us about results.

edit: Are you sure that rigidbody you are using is not null?

CodePudding user response:

Check if your rigidbody2D's Body type is set to static, If it is then set it to kinematic or dynamic.

Also where did you import the script to?

Your code is not the problem, I tested it myself! Although you could move MovementInput(); to the FixedUpdate. Its not required though.

  • Related