- Home /
Unity 2D addforce problem
Hello, I am trying to move my character and I assigned AddForce to "d" but it just starts moving then it stops and I need to press key again to start moving. Here is my code: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class movement : MonoBehaviour {
public Rigidbody2D rb;
public float sila;
public Animator anim;
// Use this for initialization
// Update is called once per frame
void Update () {
if (Input.GetKeyDown("d"))
{
rb.AddForce(Vector2.right * sila * Time.deltaTime,ForceMode2D.Force);
Debug.Log("key pressed");
}
if (Input.GetKeyUp("d"))
{
rb.velocity = new Vector2Int(0, 0);
Debug.Log("key released");
}
}
}
Answer by Tarkz · Mar 22, 2018 at 10:51 PM
@monstercro you use 'Input.GetKeyDown("d")', which only fires when the key is pushed down and then stops. Change that to 'Input.GetKey("d")' instead. This will fire while the 'd' key is active. public class movement : MonoBehaviour { public Rigidbody2D rb; public float sila; public Animator anim; // Use this for initialization // Update is called once per frame void Update () { if (Input.GetKey("d")) { rb.AddForce(Vector2.right * sila * Time.deltaTime,ForceMode2D.Force); Debug.Log("key pressed"); } if (Input.GetKeyUp("d")) { rb.velocity = new Vector2Int(0, 0); Debug.Log("key released"); } } }