[英]Raycast in Unity2D can't seem to find the floor
我目前正在尝试使用raycast通知我的游戏,何时我的角色在空中,或者更重要的是当他在地面上时。 一个简单的raycast应该可以解决问题,但是无论我尝试什么,它都会不断返回false。 我的播放器和地板上都装有对撞机,这是相关代码。
var leftKey: KeyCode;
var rightKey: KeyCode;
var jumpKey: KeyCode;
var playerSpeed = 7;
var onFloor = false;
var distToGround: float;
function Start () {
// get the distance to ground
distToGround = GetComponent.<Collider2D>().bounds.extents.y + 0.1f;
}
function IsGrounded(): boolean {
return Physics.Raycast(GetComponent.<Collider2D>().bounds.center, Vector3.down, distToGround, 1 << 8);
}
function Update () {
Debug.Log("" + IsGrounded());
if (IsGrounded()){
if(Input.GetKey(leftKey)){
GetComponent.<Rigidbody2D>().velocity.x = playerSpeed * -1;
} else if(Input.GetKey(rightKey)){
GetComponent.<Rigidbody2D>().velocity.x = playerSpeed;
}
if(Input.GetKeyDown(jumpKey)){
GetComponent.<Rigidbody2D>().AddForce(new Vector2(0,380));
}
} else if (!IsGrounded()) {
if(Input.GetKey(leftKey)){
GetComponent.<Rigidbody2D>().AddForce(new Vector2(-2,0));
} else if(Input.GetKey(rightKey)){
GetComponent.<Rigidbody2D>().AddForce(new Vector2(2,0));
}
}
}
我已经坚持了好一阵子了,我可以肯定我只是一个白痴,他缺少一些简单的东西,或者我一直在阅读过时的材料。
两件事情:
您的IsGrounded()
函数有一个错字。 它应该是GetComponent<Collider2D>()
,而不是GetComponent.<Collider2D>()
尝试增加distToGround
浮点的值,以防万一RayCast朝正确的方向前进,但距离还不够远。
希望对您有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.