由于您的玩家具有刚体,因此您可以通过刚体速度而不是通过其变换来移动玩家。
(这也使得它更加一致,因为你的跳跃的实现使用刚体)
速度是由Direction
and Speed
;由于速度是恒定的,您可以让按钮设置运动的方向。
由于您希望玩家按住按钮才能移动,因此您可以设置移动方向OnPointerDown
,并在以下情况下重置它:OnPointerUp
发生,就像这样:
Move2D.cs
public class Move2D : MonoBehaviour {
// ...
[SerializeField]
private float speed;
private Rigidbody2D rigidBody;
private Vector2 currentMoveDirection;
private void Awake() {
rigidBody = GetComponent<Rigidbody2D>();
currentMoveDirection = Vector2.zero;
}
// ...
private void FixedUpdate() {
rigidBody.velocity = (currentMoveDirection + new Vector2(0f, rigidBody.velocity.y)).normalized * speed;
}
public void TriggerMoveLeft() {
currentMoveDirection += Vector2.left;
}
public void StopMoveLeft() {
currentMoveDirection -= Vector2.left;
}
public void TriggerMoveRight() {
currentMoveDirection += Vector2.right;
}
public void StopMoveRight() {
currentMoveDirection -= Vector2.right;
}
}
PlayerMoveButton.cs
(或者你的ContinuesButton.cs
)
public class PlayerMoveButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
[SerializeField]
private Button targetButton;
[SerializeField, Tooltip("The targeted player's movement component")]
private Move2D playerMovement;
[SerializeField, Tooltip("True if this button moves the player to the left")]
private bool movesLeft;
// ...
public void OnPointerDown(PointerEventData eventData) {
if (movesLeft) {
playerMovement.TriggerMoveLeft();
} else {
playerMovement.TriggerMoveRight();
}
}
public void OnPointerUp(PointerEventData eventData) {
if (movesLeft) {
playerMovement.StopMoveLeft();
} else {
playerMovement.StopMoveRight();
}
}
}
Example:
LeftButton
现在被点击(OnPointerDown
), currentMoveDirection
被设定为Left (-1, 0)
.
松开按钮的那一刻(OnPointerUp
), the currentMoveDirection
已重置为正常(0, 0)
玩家通过设置速度来不断移动currentMoveDirection * speed
Edit
并且为了保存jump
运动,而不是简单地做currentMoveDirection * speed
,您需要向其添加当前的向上方向,如下所示:
private void FixedUpdate() {
rigidBody.velocity = (currentMoveDirection + new Vector2(0f, rigidBody.velocity.y)).normalized * speed;
}