Unity 坦克动荡的碰撞反弹

本文介绍了一个使用Unity实现的射线碰撞检测脚本。该脚本通过发射射线并在遇到带有特定标签的障碍物(如墙壁)时进行反射处理。反射遵循光的反射定律,并在每个碰撞事件中更新射线的方向。

把这个脚本挂在球上就完事了

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ray : MonoBehaviour
{
    public float Speed;
    public Vector3 direction;
    public Vector3 OUT;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        Debug.DrawLine(transform.position, transform.position + direction * 10, Color.red);
        Ray ray = new Ray(transform.position, direction);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
        {
            if (hit.collider.tag == "wall")
            {                          
                float normalAngle = (hit.transform.eulerAngles.z + 180) * Mathf.Deg2Rad;
                //法线的角度值与横杆相差90°,Mathf.Deg2Rad是一个常数,可直接将角度值转化为弧度值
                Vector3 nor = new Vector3(Mathf.Cos(normalAngle), Mathf.Sin(normalAngle), 0);
                if (Vector3.Angle(direction,nor)<90)
                {
                    nor = -nor;                 
                }
                Debug.DrawLine(hit.point, nor * 100 + hit.point);
                OUT = Vector3.Reflect(direction, nor);
                Debug.DrawLine(hit.point, hit.point + OUT,Color.green);
            }
        }
    }

    private void FixedUpdate()
    {
        this.transform.Translate(direction * Speed * Time.fixedDeltaTime, Space.World);
    }

    private void OnCollisionEnter(Collision collision)
    {
        direction = OUT;
    }
}

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值