简体   繁体   中英

How to make an object moves by holding a key on the keyboard down (ex: 'W' key) in Unity using C#?

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);
        }
    }
}

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;
        }
    }
}

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;
    //}
}

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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM