如何通过按一下按钮来移动玩家基于操纵杆的方向旋转

问题描述 投票:0回答:1

1 号是操纵杆(工作正常)

数字 2 是需要按下以使对象移动的按钮

仅当按下按钮时才根据操纵杆方向移动对象(如果对象静止或移动)的代码是什么?enter image description here

c# unity-game-engine 2d
1个回答
0
投票

这可能是这样的:

/** rigidbody for the ship for physics */
public Rigidbody2D rb;
/** the force for the thrusters or something */
public float thrustForce;

/** The current joystick input vector */
private Vector2 _direction = Vector2.zero;
/** is the thrusting button held? */
private bool _thrusting = false;

/** in which we obtain the current state of the inputs */
void Update()
{
  // ...
  
  // get current direction (normalizing it if the magnitude is greater than 1)
  Vector2 rawDir = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));

  // (n^2) > 1 only if n > 1
  // (so we can check the more efficient .sqrMagnitude instead of .magnitude)
  if (rawDir.sqrMagnitude > 1) 
  {
    _direction = rawDir.normalized;
  }
  else
  {
    _direction = rawDir;
  }

  // if you don't care about analog 'not fully tilting
  // the stick in a certain direction' inputs, you can
  // just omit that if statement and make the direction
  // .normalized in all situations

  // and is the thrust button held?
  _thrusting = Input.GetButton("Thrust");
  
  // ...
}

/** and now we use those inputs for some PHYSICS!!! (wow) */
void FixedUpdate()
{
  // ...


  if (_thrusting) // if button is held
  {
    // we add the appropriate thrust force in the specified direction
    rb.AddForce(_direction * thrustForce);
  }

  // ...

}

上面的代码使用旧的输入系统,但它应该足够简单,可以重构核心逻辑,以便在您的项目使用新的输入系统时使用它。

© www.soinside.com 2019 - 2024. All rights reserved.