简体   繁体   中英

Unity3D: How do i change force when pressing 1 key then pressing another at the same time?

i want to simulate a simple thrust like effect for example (Lunar Land). i want to thrust up when pressing up arrow key then thrust left/right when pressing the appropriate arrow key but still whilst keeping up pressed.

  if (Input.GetKey(KeyCode.UpArrow))
     {
         thrust = (Vector3.up * thrustForce);
     }
     else if (Input.GetKey(KeyCode.LeftArrow))
     {
         thrust = (Vector3.left * thrustForce);
     }
     else if (Input.GetKey(KeyCode.RightArrow))
     {
         thrust = (Vector3.right * thrustForce);
     }
     else
     {
         thrust = (Vector3.zero);
     }        

this is what i started with, and then started to add multiple "IF" statements which still did not move right. basically below, when i press UP the object thrusts up OK, but will not move left\\right until i let go of UP and press left\\right again.

i know this is probably a simple code issue

The reason this won't work, is that it will only execute ONE of the statements, since you have and else if. You need plain IFs like this:

bool keyHold = false;

if (Input.GetKey(KeyCode.UpArrow))
{
    thrust = (Vector3.up * thrustForce);
    keyHold = true;
}
if (Input.GetKey(KeyCode.LeftArrow))
{
    thrust = (Vector3.left * thrustForce);
    keyHold = true;
}
if (Input.GetKey(KeyCode.RightArrow))
{
    thrust = (Vector3.right * thrustForce);
    keyHold = true;
}

if(!keyHold) {
    thrust = (Vector3.zero);
}

This is a pretty simple fix. Your code currently goes inside the if for the up arrow when it's held, and because you use else if s, the code doesn't even try to check for the other arrow keys. If you're not holding up, then it checks for left arrow, then right and so on, stopping if one of those keys are pressed and jumping over everything after.

In addition, because you're using = on your thrust, the statements inside the ifs will just override previous stuff too, such that if you went into all ifs, only the last reached thrust will be applied, overwriting your previous sets.

Therefore, you have two minor issues: else if s and using = instead of adding on thrust. A possible fix would be something like:

thrust = Vector3.Zero; //Start with zero

if (Input.GetKey(KeyCode.UpArrow))
{
    thrust += Vector3.up * thrustForce; //Add on up thrust
}
if (Input.GetKey(KeyCode.LeftArrow))
{
    thrust += Vector3.left * thrustForce; //Add on left thrust
}
if (Input.GetKey(KeyCode.RightArrow))
{
    thrust += Vector3.right * thrustForce; //Add on right thrust
}

And if you hold left and right simultaneously, they just cancel each other out without the need for any checks.

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