我正在 Unity 中编写 2D 平台游戏,并试图让玩家停留在移动平台上。我已经搜索和修补了一两天了,但我没有任何运气。
基本上,我被告知要在角色接触时尽量让角色随着平台移动。首先,如果我使用与 OnTriggerEnter() 相关的任何内容,玩家将直接通过平台。如果我执行 OnCollisionEnter()(在播放器上使用 CharacterController,在平台上使用 BoxCollider),则什么也不会发生。这是我发现建议最多的两件事。另一个是用平台养育玩家,但这显然会导致“问题”(经常说,从未解释过)。
那么,我怎样才能让玩家留在移动平台上呢?这是移动平台的代码:
public class MovingPlatform : MonoBehaviour
{
private float useSpeed;
public float directionSpeed = 9.0f;
float origY;
public float distance = 10.0f;
// Use this for initialization
void Start ()
{
origY = transform.position.y;
useSpeed = -directionSpeed;
}
// Update is called once per frame
void Update ()
{
if(origY - transform.position.y > distance)
{
useSpeed = directionSpeed; //flip direction
}
else if(origY - transform.position.y < -distance)
{
useSpeed = -directionSpeed; //flip direction
}
transform.Translate(0,useSpeed*Time.deltaTime,0);
}
这里是玩家移动的代码(更新中):
CharacterController controller = GetComponent<CharacterController>();
float rotation = Input.GetAxis("Horizontal");
if(controller.isGrounded)
{
moveDirection.Set(rotation, 0, 0); //moveDirection = new Vector3(rotation, 0, 0);
moveDirection = transform.TransformDirection(moveDirection);
//running code
if(Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) //check if shift is held
{ running = true; }
else
{ running = false; }
moveDirection *= running ? runningSpeed : walkingSpeed; //set speed
//jump code
if(Input.GetButtonDown("Jump"))
{
//moveDirection.y = jumpHeight;
jump ();
}
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
编辑:我认为这可能与我如何定义播放器和平台有关,但我尝试了不同的组合。如果平台是一个触发器(在它的对撞机上),玩家会一直通过它。如果没有,我不能使用 OnTrigger 函数。我在播放器和平台上都有一个刚体,但它似乎没有影响任何东西。当玩家在某些设置中确实进入平台时,他会感到不安,并且经常会以失败告终。