Raycast在Unity 2D中未检测到静止对象。

huangapple go评论118阅读模式
英文:

Raycast Not Detecting idle object in unity 2d

问题

我正在制作一个Unity的2D平台游戏。我尝试创建一个敌人,当他遇到墙壁或在平台边缘时会向前移动并转向,所以我给了他这个原型脚本:

public float speed;
public float raylength;
private Rigidbody2D rb;
private int dir = -1;

void Start()
{
    rb = GetComponent<Rigidbody2D>();
}

void FixedUpdate()
{
    rb.velocity = new Vector2(speed * dir, rb.velocity.y);
    RaycastHit2D hit = Physics2D.Raycast(transform.position, new Vector2(dir, 0), raylength);
    if(hit.collider != null && hit.collider.gameObject.name!="Slime")
        print(hit.collider.gameObject.name);
    if (hit.collider.gameObject.tag=="Ground")
    {
        dir*=-1;
    }
}

由于某种原因,只有当玩家移动时,史莱姆才会打印出"player",而只有在几秒钟后进入地面时,才会打印出"ground"。我尝试将他的速度设为0并让玩家与他碰撞,但只有当他与射线的起点碰撞时才会打印"player",尽管我尝试将射线长度设置为很大的数字,但结果都一样。如果您对刚体(rigidbody)和盒子碰撞器(box collider)的值感兴趣,我已激活了盒子碰撞器中的"Is Trigger"选项,并使它成为了运动学(kinematic)的。

英文:

I am making a 2d platformer game in unity. I'm trying to create an enemy moves forward and turn when he meets a wall or on the edge of the platform so I gave him this prototype script

public float speed;
public float raylength;
private Rigidbody2D rb;
private int dir = -1;
// Start is called before the first frame update
void Start()
{
    rb = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void FixedUpdate()
{
    rb.velocity = new Vector2(speed * dir, rb.velocity.y);
    RaycastHit2D hit = Physics2D.Raycast(transform.position, new Vector2(dir, 0), raylength);
    if(hit.collider != null && hit.collider.gameObject.name!="Slime")
        print(hit.collider.gameObject.name);
    if (hit.collider.gameObject.tag=="Ground")
    {
        dir*=-1;
    }
}

for some reason the slime only prints player when the player is moving and only prints ground when he enters the ground after few seconds I tried setting his speed to 0 and making the player collide with it but it only print player when he collides with the origin of the raycast althought i tried to set the ray length to insane numbers but same result.
if you are interested in the values of the rigidbody and the box collider so i activated is trigger in the box collider and made him kinematic

答案1

得分: 0

Raycast 只会检测到一个物体,我认为你的代码是从射线发出的位置检测物体。进入编辑 > 项目设置 > 物理 2D > 取消选中“在碰撞体内开始查询”。现在,你的 Raycast 应该能够检测到父对象外部的物体。

英文:

Raycast will detect only one object, I think yours is detecting the object from where ray is originating. Go to Edit>Project settings>Physics2d> Uncheck Queries start in Colliders.

Now your Raycast should detect objects outside your parent object.

huangapple
  • 本文由 发表于 2023年7月3日 03:29:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76600480.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定