unity3d射线实现

 

射线检测故名就是通过射线去检测是否和碰撞器产生了交集,和碰撞器与碰撞器发生交集一样,会返回一个真。

物体要碰撞器

 

Pox X是相对于父容器的位置。

改变对 transform.position没影响

 

Physics2D.Raycast射线检测

RaycastHit2D onGround2 = Physics2D.Raycast(transform.position, -Vector2.up);
print(onGround2.distance);

transform.position是世界坐标 ,是物体中心点

获取到的distance都是0 因为与自己碰撞了 。 所以要将发射点下移

 

示例

    private void FixedUpdate() {
        Vector3 front = new Vector3(-1, 0, 0);
        if (transform.localScale.x < 0) {
            front = new Vector3(1, 0, 0);
        }

        Vector3 beg = transform.position + new Vector3(0, 0, 0);
        Vector3 down = new Vector3(0, -1, 0);
        
        // 向运动方向的射线
        Debug.DrawLine(beg, beg + front * 0.2f,Color.red);
        if (Physics2D.Raycast(beg, front, 0.2f, LayerMask.GetMask("Default"))) {
            transform.localScale = new Vector3(transform.localScale.x * -1, transform.localScale.y);
        }
        
        // 斜下方的射线
        Debug.DrawLine(beg, beg + (front+down).normalized * 0.8f,Color.red);
        if (!Physics2D.Raycast(beg, front+down, 0.2f, LayerMask.GetMask("Default"))) {
            transform.localScale = new Vector3(transform.localScale.x * -1, transform.localScale.y);
        }
        
        rigid.velocity = new Vector2(front.x * speed, rigid.velocity.y);
    }

移动物体设置layer为Enemy

实现前方和斜下方的2条射线 ,实现怪来回移动

 

Physics2D.OverlapCircle

检测某个碰撞体是不是在某个圆形区域内,返回碰撞体,如果有多个,返回z轴最小的碰撞体,若没有返回false

 

要注意用 1<<

    // 攻击范围的球形射线
        Collider2D[] hits = Physics2D.OverlapCircleAll(this.transform.position, attackDis, 1<<LayerMask.NameToLayer("hero"));
        foreach (var hit in hits) {
            var attribute = hit.transform.GetComponent<Attribute>();
            if (attribute != null) {
                attribute.addLife(-5);
            }
        }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值