其他分享
首页 > 其他分享> > Unity3D_类捕鱼项目,子弹反弹效果实现

Unity3D_类捕鱼项目,子弹反弹效果实现

作者:互联网

子弹反弹示意图如下:

1.墙体与子弹均为碰撞体

2.前提条件:需要知道子弹前进方向向量,墙体方向向量

3.计算简易过程,黄色为子弹方向向量,计算出与墙的夹角,根据入射角等于反射角算出橙色方向向量。此时只是子弹方向改变了,接下来还要算出位置的偏移量,根据与墙夹角与子弹本身的大小由三角函数sin/cos算出偏移量,最终效果如红色箭头。

代码:

-- 子弹反弹,ColliderObj:碰撞墙体共4面,AmmoLength:子弹长度估算值,备注:self.Dir为子弹当前的方向向量,self.o_Transform为子弹实例,
function AmmoBase:ReflectBullet(ColliderObj, AmmoLength)

    local inNormal = nil
    local wallNormal = nil
    local XOrZ = true
    if tostring(ColliderObj.transform.name) == "ForwardWall" then
        inNormal = Vector3(0, 0, -1)
        wallNormal = Vector3(1, 0, 0)
        XOrZ = true
    elseif tostring(ColliderObj.transform.name) == "BackWall" then
        inNormal = Vector3(0, 0, 1)
        wallNormal = Vector3(1, 0, 0)
        XOrZ = true
    elseif tostring(ColliderObj.transform.name) == "LeftWall" then
        inNormal = Vector3(1, 0, 0)
        wallNormal = Vector3(0, 0, 1)
        XOrZ = false
    elseif tostring(ColliderObj.transform.name) == "RightWall" then
        inNormal = Vector3(-1, 0, 0)
        wallNormal = Vector3(0, 0, 1)
        XOrZ = false
    end
    if inNormal == nil then
        return
    end

    local wallAngle = Vector3.Angle(self.Dir, wallNormal)
    local reflexDir = Vector3.Reflect(self.Dir,inNormal)
    local dirAngle = 180 - Vector3.Angle(self.Dir, reflexDir)
    local dic = math.sin(math.rad(dirAngle)) * AmmoLength 
    
    -- log(tostring(wallAngle) .. "  与墙夹角")
    -- log(tostring(reflexDir) .. "  矫正向量")
    -- log(tostring(dirAngle) .. "  反射夹角")
    -- log(tostring(dic) .. "  位置矫正")

    local pos = self.o_Transform.position
    if XOrZ then
        if wallAngle > 90 then
            self.o_Transform.position = Vector3(pos.x - dic, pos.y, pos.z)
        else
            self.o_Transform.position = Vector3(pos.x + dic, pos.y, pos.z)
        end
    else
        if wallAngle > 90 then
            self.o_Transform.position = Vector3(pos.x, pos.y, pos.z - dic)
        else
            self.o_Transform.position = Vector3(pos.x, pos.y, pos.z + dic)
        end
    end
   
    self.Dir = reflexDir
    self.o_Transform.rotation = Quaternion.FromToRotation(Vector3.forward, self.Dir) -- 方向矫正

end

 

标签:Unity3D,Vector3,捕鱼,self,子弹,pos,tostring,local
来源: https://blog.csdn.net/Le_Sam/article/details/101468402