我希望碰撞的球应该开始向反方向移动。现在我的球刚刚停止检测到碰撞

时间:2014-12-03 20:05:16

标签: c# unity3d collision-detection raycasting

public class moveBall : MonoBehaviour {

private const float SPEED = 5f;
private Vector3 direction;
private Vector3 inversedirection;
private float distance =0f;
private Vector3 lastPos;
private RaycastHit hit = new RaycastHit();


// Use this for initialization
void Start () {
    direction = (new Vector3( 1.0f, 0.0f, 0.0f)).normalized;
    inversedirection = (new Vector3 (-1.0f, 0.0f, 0.0f)).normalized;
    lastPos = transform.position;

}

// Update is called once per frame
void Update () {
    transform.position += direction * SPEED * Time.deltaTime;

    lastPos = transform.position;
    Debug.DrawRay (transform.position, direction * 2,  Color.green);
    if (Physics.Raycast (transform.position, direction, out hit, 2)) {
                    Debug.Log ("Hit");
                    print (lastPos.x);
                    if (hit.collider.gameObject.name == "Plane") {
                            Destroy (this);
                    }
            }


}
}

请帮忙。如果有人可以建议我如何继续。我希望那个球碰撞飞机和方向相反的方向。我正在使用Raycast来检测碰撞。

1 个答案:

答案 0 :(得分:1)

我不熟悉Unity,所以我不确定Destroy(this);做了什么(我猜可以),但是如果你想要在击中飞机时球反弹,你需要改变方向球而不是破坏当前的物体。也许像

这样的东西
if (hit.collider.gameObject.name == "Plane") {
    direction = inversedirection;
    inversedirection = direction;
}

或者只删除整个inversedirection变量并写入

if (hit.collider.gameObject.name == "Plane")
    direction *= -1;

也就是说,这只有在球总是垂直于飞机行进时才有效。否则,您必须反映平面法线中的方向向量,而不是反转方向。