【发布时间】:2020-01-17 11:04:01
【问题描述】:
我正在开发一个2D 平台游戏,其中角色是一个球,应该能够左右移动和跳跃。它现在可以做到这一切,但出于某种我不明白的原因(因为我 对 Unity 完全陌生)有时 它会像重力为负数一样飞起来。
这是我的第一个脚本的代码Move2D:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move2D : MonoBehaviour
{
public float moveSpeed = 5f;
public bool isGrounded = false;
[SerializeField] private Rigidbody2D rigidbody;
private Vector2 currentMoveDirection;
private void Awake()
{
rigidbody = GetComponent<Rigidbody2D>();
currentMoveDirection = Vector2.zero;
}
public void Jump()
{
if (isGrounded)
{
rigidbody.AddForce(new Vector3(0f, 5f), ForceMode2D.Impulse);
}
}
private void FixedUpdate()
{
rigidbody.velocity = (currentMoveDirection + new Vector2(0f, rigidbody.velocity.y)).normalized * moveSpeed;
}
public void TriggerMoveLeft()
{
currentMoveDirection += Vector2.left;
}
public void StopMoveLeft()
{
currentMoveDirection -= Vector2.left;
}
public void TriggerMoveRight()
{
currentMoveDirection += Vector2.right;
}
public void StopMoveRight()
{
currentMoveDirection -= Vector2.right;
}
}
这是第二个脚本的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ContinuesButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
[SerializeField] private Button targetButton;
[SerializeField] private Move2D playerMovement;
[SerializeField] private bool movesLeft;
private readonly bool isHover;
private void Awake()
{
if (!targetButton) targetButton = GetComponent<Button>();
}
public void OnPointerDown(PointerEventData eventData)
{
if (movesLeft)
{
playerMovement.TriggerMoveLeft();
} else
{
playerMovement.TriggerMoveRight();
}
}
public void OnPointerUp(PointerEventData eventData)
{
if (movesLeft)
{
playerMovement.StopMoveLeft();
} else
{
playerMovement.StopMoveRight();
}
}
}
我注意到,一旦运动控制器或一些对撞机让它稍微上升一点,球就会开始飞起来。例如,当我让它跳跃时,它会一直向上,或者当我在游戏中尝试让它“走”上山时,它会立即开始向上飞。
非常感谢任何帮助或信息,我真的没有看到问题。
【问题讨论】:
-
我认为您的问题来自您的 FixedUpdate 方法:
rigidbody.velocity = (currentMoveDirection + new Vector2(0f, rigidbody.velocity.y)).normalized * moveSpeed; -
每帧添加一个
y速度,与前一帧相同。 -
@EnricoCortinovis .. 可能不是每帧都添加它?简而言之,您每次都将 Y 速度加倍.. 不确定您的目标是什么
-
@derHugo 我想在按下左右按钮时让球连续移动。