Home > database >  Top down game in Unity. Player can't stop moving
Top down game in Unity. Player can't stop moving

Time:12-30

i've following issue. I'm trying to make game with top down view (something like first GTA game). The problem is when i press the key my player is moving, but can't stop. Here you can see my script:

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

public class PlayerMovemenet : MonoBehaviour
{
    private Rigidbody2D m_Rigidbody;
    private Transform playerTransform;
    public float m_Speed = 100.0f;
  

    // Start is called before the first frame update

    void Start()
    {
        m_Rigidbody = GetComponent<Rigidbody2D>();
        playerTransform = GameObject.Find("Player").transform;
        
    }

    // Update is called once per frame
    void FixedUpdate()
    {

        Vector3 playerPos = playerTransform.eulerAngles;

        if (Input.GetKey(KeyCode.UpArrow))
        {   
            m_Rigidbody.velocity= transform.up * Time.deltaTime * m_Speed;
            
        }



            if (Input.GetKey(KeyCode.DownArrow))
            {
                
                m_Rigidbody.velocity = transform.up * Time.deltaTime * (-m_Speed);
            
            }



            if (Input.GetKey(KeyCode.RightArrow))
            {
                 transform.Rotate(0, 0, -1 * m_Speed * Time.deltaTime);
            }

        if (Input.GetKey(KeyCode.LeftArrow))
        {
            transform.Rotate(0, 0, 1 * m_Speed * Time.deltaTime);

        }
        }


    }

'''

Can you please tell me how to fix it? Thanks for your answers.

CodePudding user response:

Note that in general a velocity already is a value in absolute units per second and you don't want to multiply by Time.deltaTime in that case.

Also in general whenever dealing with Physics I wouldn't use transform at all but rather do everything via the Rigidbody.

And then simply when you don't press a key do

if (Input.GetKey(KeyCode.UpArrow))
{   
    m_Rigidbody.velocity = Quaternion.Euler(0, 0, m_Rigidbody.rotation) * Vector3.up * m_Speed;
}
else if (Input.GetKey(KeyCode.DownArrow))
{           
    m_Rigidbody.velocity = Quaternion.Euler(0, 0, m_Rigidbody.rotation) * Vector3.down * m_Speed;
}
else
{
    m_Rigidbody.velocity = Vector2.zero;
}

For the rotation I would also rather go

m_Rigidbody.rotation  = m_Speed * Time.deltaTime;

and

m_Rigidbody.rotation -= m_Speed * Time.deltaTime;
  • Related