如何避免我的播放器跳过对象?

时间:2016-08-28 19:25:50

标签: c# unity3d

当我的玩家跳到一个物体前面时,它会直接穿过它,我不知道如何解决它。我知道这是因为我正在使用变换来移动我的播放器,但这是最简单的跳跃方式所以我不想改变它。这是我移动播放器的代码:

using UnityEngine;
using System.Collections;

public class MovePlayer : MonoBehaviour
{   
    private Vector3 newPos;
    private Vector3 up = new Vector3 (0, .3f, 0);
    private bool jumping = false;
    public Rigidbody rigidbody;

    void Start(){
        rigidbody = GetComponent<Rigidbody> ();
    }

    void Update(){
        rigidbody.freezeRotation = true;

        if (!jumping) {
            if (Input.GetKeyDown (KeyCode.UpArrow)) {
                newPos = Vector3.forward + transform.position;
                transform.rotation = Quaternion.Euler (0, 0, 0);
                transform.position = (newPos);
                transform.position = newPos + up;               
            } 
            if (Input.GetKeyDown (KeyCode.DownArrow)) {
                newPos = Vector3.back + transform.position;
                transform.rotation = Quaternion.Euler (0, 180, 0);
                transform.position = (newPos);
                transform.position = newPos + up;
            }

            if (Input.GetKeyDown (KeyCode.RightArrow)) {
                newPos = Vector3.right + transform.position;
                transform.rotation = Quaternion.Euler (0, 90, 0);
                transform.position = (newPos);
                transform.position = newPos + up;
            }
            if (Input.GetKeyDown (KeyCode.LeftArrow)) {
                newPos = Vector3.left + transform.position;
                transform.rotation = Quaternion.Euler (0, -90, 0);
                transform.position = (newPos);
                transform.position = newPos + up;
            }               
        }
    }

    void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.CompareTag ("Ground")) 
            jumping = false;
    }

    void OnCollisionExit(Collision other)
    {
        if (other.gameObject.CompareTag("Ground"))
            jumping = true;
    }
}

2 个答案:

答案 0 :(得分:0)

你的问题是你正在对玩家位置应用变换 - 你真的需要计算从当前位置到变换隐含的目的地的路线,然后对每个中间点进行碰撞检测。

这是网上很多例子的问题,但谷歌搜索Unity碰撞检测会提出很多例子。

答案 1 :(得分:0)

由于这是一个附有Rigidbody的GameObject,并且您希望在移动时检测到碰撞,因此您必须使用MovePositionMoveRotation函数而不是移动其here 1}}组件直接。

因此,transformtransform.position = newPos + up;等代码必须更改为transform.rotation = Quaternion.Euler (0, 180, 0);rigidbody.MovePosition(newPos + up);

启用rigidbody.MoveRotation(Quaternion.Euler(0, 180, 0));插值以平滑移动GameObject。此外,Rigidbody必须为真/启用,否则使用isKinematicMovePosition将无用,只需将MoveRotation移至Rigidbody ...

transform.position