Home > other >  How to make an object moves by holding a key on the keyboard down (ex: 'W' key) in Unity u
How to make an object moves by holding a key on the keyboard down (ex: 'W' key) in Unity u

Time:10-31

I need the object moves only when I'm holding W key on the keyboard and once I release the key, It must be stop smoothly.

Here is my code:

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

public class Car : MonoBehaviour
{
    public Rigidbody rb;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.W))
        {
            rb.AddForce (transform.forward*100*Time.deltaTime);
        }
    }
}

CodePudding user response:

Do you mean you want to call rb.AddForce once ? Fix it like this, by add a variable isMoving:

public class Car : MonoBehaviour
{
    private bool isMoving;
    public Rigidbody rb;
    // Start is called before the first frame update
    void Start()
    {
        isMoving = false;
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.W) && !isMoving)
        {
            rb.AddForce (transform.forward*100*Time.deltaTime);
            isMoving = true;
        }
    }
}

CodePudding user response:

Input.GetKeyDown is only true ONCE in the frame where the button is pressed.

It sounds like you rather want to use Input.GetKey which is true every frame WHILE the button stays pressed.

In general though you should apply forces etc rather in FixedUpdate

void FixedUpdate()
{
    if(Input.GetKey(KeyCode.W))
    {
        rb.AddForce(rb.GetRelativeVector(Vector3.forward) * 100 * Time.deltaTime);
    }
    // If you want it to stop immediately - not very realistic though
    // and would require more checks like is it actually on the ground etc
    //else
    //{
    //    rb.velocity = Vector3.zero;
    //}
}

CodePudding user response:

Try using GetKey instead of GetKeyDown

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

public class Car : MonoBehaviour
{
    public Rigidbody rb;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.W))
        {
            rb.AddForce (transform.forward*100*Time.deltaTime);
        }
    }
}
  • Related