Home > front end >  Why does my player go quicker to the back then to the front
Why does my player go quicker to the back then to the front

Time:01-09

I'm making something in unity and I can walk to the front, the left and the right but whenever I try to go backwards my player goes way faster despite them being coded the same way. I'm pretty new so I have no idea why this isn't working. Anyone has a similar problem?

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

public class Walk : MonoBehaviour
{
    public Rigidbody rb;
    private bool moving;
    public float Speed;

    void Update()
    {

        if (Input.GetKey("right"))
        {
            rb.AddForce(Speed*Vector3.right);
            moving = true;
        }
        else{moving = false;}

        if (Input.GetKey("left"))
        {
            rb.AddForce(Speed*Vector3.left);
            moving = true;
        }
        else{moving = false;}
        
        if (Input.GetKey("up"))
        {
            rb.AddForce(Speed*Vector3.forward);
            moving = true;
        }
        else{moving = false;}

        if (Input.GetKey("down"))
        {
            rb.AddForce(Speed*Vector3.back);
            moving = true;
        }
        else{moving = false;}

        if (moving)
        {
            moving = true;
        }
        else{rb.velocity = Vector3.zero;}

    }
}

CodePudding user response:

Try this instead:


private Rigidbody _rigidbody;

private float _movementForce = 10f;
private double _maximumVelocity = 10f;

private void Awake() => _rigidbody = GetComponent<Rigidbody>();

private void Update(){

    if(_rigidbody.velocity.magnitude >= _maximumVelocity)
        return;
    
    if(Input.GetKey("up"))
        _rigidbody.AddForce(_movementForce * transform.forward);

    if(Input.GetKey("down"))
        _rigidbody.AddForce(_movementForce * -transform.forward); // -forward gives u back

    if(Input.GetKey("left"))
        _rigidbody.AddForce(_movementForce * -transform.right);

    if(Input.GetKey("right"))
        _rigidbody.AddForce(_movementForce * transform.right);

}
  •  Tags:  
  • Related