【发布时间】:2021-05-25 16:23:53
【问题描述】:
我的目标是: Launching Ray> Ray found Collider> 添加这个对撞机变量> 创建Veсtor2.Lerp,其中的端点是一个transform the collider,找到了。 该脚本有效,但不是应有的。玩家不动 (对不起,愚蠢的错误,我是初学者)
public class move : MonoBehaviour
{
private float speed = 150f;
private Rigidbody2D rb2d;
Transform EndPoint;
private bool ready;
void Start() {
rb2d = GetComponent<Rigidbody2D>();
}
void Update() {
MoveInfoInsert();
}
void FixedUpdate() {
Moving();
}
void MoveInfoInsert() {
if(Input.GetAxisRaw("Horizontal") != 0) {
rb2d.constraints = RigidbodyConstraints2D.FreezePositionY;
ready = true;
if(Input.GetAxisRaw("Horizontal") > 0) {
RaycastHit2D RightHit = Physics2D.Raycast(transform.position, transform.right * 1000f, LayerMask.GetMask("FinishForMove"));
if(RightHit.collider != null) {
EndPoint = RightHit.transform;
}
}
else {
RaycastHit2D LeftHit = Physics2D.Raycast(transform.position, -transform.right * 1000f, LayerMask.GetMask("FinishForMove"));
if(LeftHit.collider != null) {
EndPoint = LeftHit.transform;
}
}
}
if(Input.GetAxisRaw("Vertical") != 0) {
rb2d.constraints = RigidbodyConstraints2D.FreezePositionX;
ready = true;
if(Input.GetAxisRaw("Vertical") > 0) {
RaycastHit2D UpHit = Physics2D.Raycast(transform.position, transform.up * 1000f, LayerMask.GetMask("FinishForMove"));
if(UpHit.collider != null) {
EndPoint = UpHit.transform;
}
}
else {
RaycastHit2D DownHit = Physics2D.Raycast(transform.position, -transform.up * 1000f, LayerMask.GetMask("FinishForMove"));
if(DownHit.collider != null) {
EndPoint = DownHit.transform;
}
}
}
}
void Moving() {
if(ready == true) {
Vector2.Lerp(transform.position, EndPoint.position, Time.fixedDeltaTime * speed);
rb2d.constraints = RigidbodyConstraints2D.FreezeRotation;
}
}
}
【问题讨论】:
-
一般来说,你应该简单地设置和重置(设置
null)EndPoint,而不是ready,然后使用if(EndPoint) -
@derHugo,我试过你写的。不工作。我还决定尝试进行“检查”(在控制台中),并注意到 RayCast 正在注册甚至不存在的对撞机。也许是他们?也许我以某种方式错误配置了它们?
-
我找到了解决问题的方法。感谢 derHugo 和 Armin。首先,事实证明,在下一个参数中,您需要指定光线的长度,并且方向本身不需要乘以 1000。其次,我遇到了层的问题,我解决了。我也遇到了 ready 变量的问题,它根本不需要,只会干扰工作。 if也有一点问题