我是 Unity 和 C# 的新手,但我想提供帮助,因此我尝试模拟您的游戏以获得解决方案,并且使用此脚本作为 Player 运动我没有遇到任何问题(您可以修改变量为例如,为跳跃速度添加一个单独的变量以使其更平滑等)
public class Player : MonoBehaviour {
Rigidbody2D rb;
float speed = 7f;
Vector3 movement;
public bool isOnGround;
public bool isOnPlatform;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.position += movement * speed * Time.deltaTime;
Jump();
}
void Jump()
{
if (Input.GetButtonDown("Jump") && isOnGround || Input.GetButtonDown("Jump") && isOnPlatform)
{
rb.AddForce(transform.up * speed, ForceMode2D.Impulse);
}
}
}
同时添加一个空的子对象到你的 Player 游戏对象并在他的脚下添加一个 BoxCollider2D,在 Y 轴上缩小它like this
还要将此脚本附加到该子游戏对象以检查玩家是否在地面上(使用新标签“地面”标记地面碰撞对象),这样你就不会在空中无限跳跃或玩家是否在平台上(用“平台”标记平台对撞机对象)所以你仍然可以跳下它
public class GroundCheck : MonoBehaviour {
Player player;
MovingPlatform mp;
// Start is called before the first frame update
void Start()
{
player = FindObjectOfType<Player>();
mp = FindObjectOfType<MovingPlatform>();
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "Ground")
{
player.isOnGround = true;
}
if (other.gameObject.tag == "Platform")
{
player.isOnPlatform = true;
transform.parent.SetParent(other.transform);
mp.MoveThePlatform();
}
}
private void OnCollisionExit2D(Collision2D other)
{
if (other.gameObject.tag == "Ground")
{
player.isOnGround = false;
}
if (other.gameObject.tag == "Platform")
{
transform.parent.SetParent(null);
}
}
}
最后是平台移动(没有 RigidBody2D,只是一个对撞机)
public class MovingPlatform : MonoBehaviour {
bool moving;
public Transform moveHere;
// Update is called once per frame
void Update()
{
if (moving)
{
gameObject.transform.position = Vector2.MoveTowards(transform.position, moveHere.position, 2f * Time.deltaTime);
}
}
public void MoveThePlatform()
{
moving = true;
}
}
其他图片
Player, Platform
附:忘记添加 - 在 Player 的 RigidBody2D 上,在 Constraints 下,选中“Freeze Rotation Z”框。