Home > database >  When I press W, my car starts to move but it's making a loop. I want it to play the code at onc
When I press W, my car starts to move but it's making a loop. I want it to play the code at onc

Time:10-29

When I press W, my car starts to move but it's making a loop. I want it to play the code at once.

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