Reputation: 1769
I have small game I wrote in which i have object which moving forward and turning left and right. when user press A object goes left and rotate to the left if user pres D it goes left and rotate left, i what to set rotation to 0 after user letting key up
bool slowbtn = Input.GetKey("s");
bool right = Input.GetKey("d");
if (right == true)
{
rd.AddForce(sideForce * Time.deltaTime, 0, 0,ForceMode.VelocityChange);
rd.transform.eulerAngles = new Vector3(0, 10 , 0);
}
if (Input.GetKey("a"))
{
rd.AddForce(-sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
rd.transform.eulerAngles = new Vector3(0, -10 , 0);
}
if i wan to set rotation back to 0 when user release key i am using this
if (Input.GetButtonUp("a"))
{
rd.transform.eulerAngles = new Vector3(0, 0, 0);
}
if (Input.GetButtonUp("d"))
{
rd.transform.eulerAngles = new Vector3(0, 0, 0);
}
but it doesn't work I don't understand why and also it brakes my previous code , so object if not moving forward
Upvotes: 0
Views: 1150
Reputation: 102
When I replace your
Input.GetButtonUp("a")
with
Input.GetKeyUp("a")
this works totally fine.
Did you try to debug this code for yourself? Because it was quite simple to figure out that the Input.GetButtonUp(…)
was not called by setting a breakpoint in this line.
Btw. I would consider writing your input code like this:
if (Input.GetKey("d"))
{
rd.AddForce(sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
rd.transform.eulerAngles = new Vector3(0, 10, 0);
}
else if (Input.GetKey("a"))
{
rd.AddForce(-sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
rd.transform.eulerAngles = new Vector3(0, -10, 0);
}
else
{
rd.transform.eulerAngles = new Vector3(0, 0, 0);
}
Upvotes: 1
Reputation: 649
Unity's Input.GetButtonUp and Input.GetButtonDown handle "virtual" buttons, which you set up in Input Settings. Input.GetKeyUp/Input.GetKeyDown are about keys on your keyboard. So, you should choose GetKey or GetButton but not both at the same time.
As I see, you want your object rotates during all the time user is pressing a key. I suggest you to use addition "state" property in your class:
private State state = State.IDLE;
private enum State {
LEFT, RIGHT, IDLE
};
Update your code:
if (Input.GetKeyDown(KeyCode.D)) {
state = State.RIGHT;
}
if (Input.GetKeyDown(KeyCode.A)) {
state = State.LEFT;
}
if (Input.GetKeyUp(KeyCode.D) || Input.GetKeyUp(KeyCode.A)) {
state = State.IDLE;
}
switch (state) {
case State.LEFT:
rd.AddForce(sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
rd.transform.eulerAngles = new Vector3(0, 10, 0);
break;
case State.RIGHT:
rd.AddForce(-sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
rd.transform.eulerAngles = new Vector3(0, -10 , 0);
break;
case State.IDLE:
rd.transform.eulerAngles = Vector3.zero;
break;
}
Several recommedations:
Upvotes: 2