unity中物体碰撞反弹(学习)

unity中物体碰撞反弹相关代码:

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

public class BallControl : MonoBehaviour
{
    
    
    //忽略小球第一次与玩家的碰撞
    private bool isStart; 
    //刚体组件
    private Rigidbody2D rbody;
    //上次碰撞的位置
    private Vector3 point;
    void Start()
    {
    
    
        rbody = GetComponent<Rigidbody2D>();
    }
    //开始移动
    public void StartMove()
    {
    
    
        //给球一个速度 方向 * 速度  new Vector2(1,1).normalized(单位向量)
        rbody.velocity = new Vector2(1,1).normalized * 1;
        isStart = true;
        //最开始的位置
        point = transform.position;
    }

    //当与墙壁和玩家碰撞时
    private void OnCollisionEnter2D(Collision2D collision)
    {
    
    
        if (isStart == false)
        {
    
    
            return;
        }

        if (transform.position == point)
        {
    
    
            return;
        }
        //销毁砖块
        if (collision.collider.tag == "brick")
        {
    
    
            Destroy(collision.collider.gameObject);
        }
        
        //反射
        Vector2 inVec = transform.position - point;
        point = transform.position;
        Vector2 outVec = Vector2.Reflect(inVec,collision.contacts[0].normal);
        rbody.velocity = outVec.normalized * 1;

    }

注1:

collision.contacts[0]:
public ContactPoint[] contacts
物理引擎生成的接触点。接触点存储在 Collision 结构中,每个接触均包含一个接触点、法线和碰撞的两个碰撞体

更新:应避免使用它,因为它会产生内存垃圾。改用 GetContact 或 GetContacts。

变量 作用
normal 接触点的法线。
otherCollider 在该点接触的其他碰撞体
point 接触点
separation 在该接触点的碰撞体之间的距离
thisCollider 在该点接触的第一个碰撞体。

注2:

public static Vector2 Reflect (Vector2 inDirection, Vector2 inNormal);
作用: 从法线定义的向量反射一个向量。

猜你喜欢

转载自blog.csdn.net/qq_42540393/article/details/125979557
今日推荐