我如何让角色在Unity中的移动平台上行走

问题描述

我在Unity 2020.1内置的2D Sidescroller中有一个移动平台

移动平台使用Moveto方法在两点之间转换。它没有RigidBody2D组件。

我通过使用OnCollisionEnter2D和OnCollisionExit2D将该播放器作为平台的子代,将播放器作为平台的子代,将播放器作为父代,并分别重置为null。效果很好。

我正在使用Standard Assets中的CharacterController。

问题:

当我尝试在平台上来回移动时,玩家只是走在原地。

到目前为止我已经尝试过:

  1. 通过在播放器移动矢量的x维度上添加一个常量来更改播放器的当前速度。 可以正常工作,但是该常量需要很大才能使其移动一点。这是一个巨大的漏洞,违反了每种编码的专有性。

  2. 将RigidBody2D放置在平台上。使它运动,这样当我着陆时它不会掉落到地面上。通过“ rb.veLocity = new Vector2(speed,rb.veLocity.y)”移动平台;

2a)尝试使播放器成为运动平台的孩子。 Player是一个孩子,但是它不会随平台一起移动。我相信这是因为两个对象都具有RigidBody2D组件,根据我的阅读,我收集到的这些组件不能很好地发挥作用。

2b)尝试将平台的运动矢量添加到玩家的运动矢量中,以使其停留在一个位置。玩家保持静止以确保他固定在平台上。 没有骰子。

我全都没主意了。仔细阅读视频以使玩家坚持使用移动平台,所有这些操作都使用该平台将玩家从一个地方移动到另一个地方,而没有想到游戏可能希望玩家在平台移动时在平台上来回移动。

我不敢相信这不是一个解决的问题,但是我的Google foo没有给我任何答案。

谢谢。

解决方法

我是Unity和C#的新手,但是我想提供帮助,所以我尝试模拟您的游戏以寻求解决方案,并且在使用此脚本作为Player运动时,我没有遇到任何问题(您可以将变量修改为u例如,为跳跃速度添加一个单独的变量以使其更流畅等)

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缩小范围

还将此脚本附加到该子gameObject上,以检查玩家是否在地面上(用新标签“ Ground”标记地面对撞机对象),这样您就不会在空中无限跳跃,或者玩家是否在平台上(使用“平台”标记平台对撞机对象),因此您仍然可以跳下来

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;
}

}

其他图像 PlayerPlatform

P.s。忘记添加-在Player的RigidBody2D上的“约束”下,选中“冻结旋转Z”框。