自Unity 5以来,跳转光线播放无法正常工作

时间:2015-03-20 20:56:50

标签: c# unity3d collision raycasting

我回答了一个问题,关于让玩家跳起来的光线投射,如果他们触地,我设法得到了很大的帮助并解决了我的问题。自从我的项目更新到Unity 5后,我的播放器不再跳转,并且关于它的if语句永远不会运行:

if(Physics.Raycast(ray, rayDistance, 1 << 8))

我不确定为什么会这样,回到我上次回答的问题之后,我无法解决这个问题。如果有人能提供帮助,我会非常感激,因为我还是比较新的Unity和C#。谢谢

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

// Update is called once per frame
void FixedUpdate() {

    // Creating floats to hold the speed of the plater
    float playerSpeedHorizontal = 4f * Input.GetAxis ("Horizontal");
    float playerSpeedVertical = 4f * Input.GetAxis ("Vertical");


    //Vector3 velocity = transform.forward * playerSpeedVertical + transform.right * playerSpeedHorizontal;
    //velocity.Normalize();
    //velocity *= playerMaxSpeed;
    //velocity.y = rigidbody.velocity.y;
    //rigidbody.velocity = velocity;

    // Transform statements to move the player by the playerSpeed amount.
    transform.Translate (Vector3.forward * playerSpeedVertical * Time.deltaTime);
    transform.Translate (Vector3.right * playerSpeedHorizontal * Time.deltaTime);

    // Calling the playerJump function when the jump key is pressed
    if (Input.GetButton("Jump"))
    {
        playerJump();
    }
}

/// Here we handle anything to do with the jump, including the raycast, any animations, and the force setting it's self.
void playerJump() {

    const float JumpForce = 1.75f;
    Debug.Log ("Should Jump");

    Vector3 rayOrigin = transform.position;
    rayOrigin.y += GetComponent<Collider>().bounds.extents.y; //move the ray origin up into the collider so that it won't begin in the ground / floor
    float rayDistance = GetComponent<Collider>().bounds.extents.y + 0.1f;

    Ray ray = new Ray ();
    ray.origin = rayOrigin;
    ray.direction = Vector3.down;

    if(Physics.Raycast(ray, rayDistance, 1 << 8)) {
        Debug.Log ("Jumping");
        GetComponent<Rigidbody>().AddForce (Vector3.up * JumpForce, ForceMode.VelocityChange);
    }
}
}

1 个答案:

答案 0 :(得分:1)

之前,你的代码依赖于游戏对象的位置和它的边界中心是相同的。可能当你更新到unity5时,这可能已经改变,但可能还有其他原因。

解决方案是从边界的中心检查,而不是从物体的中心(其位置)检查。因为你使用bounds.extents来获取从边界中心到边界边缘的距离,如果边界中心和gameObjects中心不同,那就不再有效了。

以下是应该执行此操作的已更改代码:

/// Here we handle anything to do with the jump, including the raycast, any animations, and the force setting it's self.
void playerJump() {

    const float JumpForce = 1.75f;
    Debug.Log ("Should Jump");

    Vector3 rayOrigin = GetComponent<Collider>().bounds.center;

    float rayDistance = GetComponent<Collider>().bounds.extents.y + 0.1f;
    Ray ray = new Ray ();
    ray.origin = rayOrigin;
    ray.direction = Vector3.down;
    if(Physics.Raycast(ray, rayDistance, 1 << 8)) {
        Debug.Log ("Jumping");
        GetComponent<Rigidbody>().AddForce (Vector3.up * JumpForce, ForceMode.VelocityChange);
    }
}
}