Unity 弹弹球反射

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

public class BallCtr : MonoBehaviour {
    [Tooltip("球移动的方向")]
    Vector3 MoveDir;
     
    Vector3 lastColPoint = Vector3.zero;
    [Tooltip("球移动的速度")]
    [SerializeField]
    private float MoveSpeed = 0.005f ;
    // Use this for initialization
    void Start () {
        GetMoveDir();

    }
    private void Update()
    {
        MoveDir = new Vector3(MoveDir.x, 0, MoveDir.z);
        transform.Translate(MoveDir * Time.deltaTime * MoveSpeed);

    }


    #region private Method

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.collider.CompareTag("Wall"))
        {
           Vector3 pos = GetColliderPoint(collision);
            Debug.Log("碰撞点: " + pos);
            Vector3 nextPoint =new Vector3((pos.x - (lastColPoint.x - pos.x)),0,lastColPoint.z);
            Debug.Log("下一个碰撞点: " + nextPoint);
            MoveDir =   (nextPoint - pos).normalized;

            lastColPoint = pos;

        }
        if (collision.collider.CompareTag("Player"))
        {
            Vector3 pos = GetColliderPoint(collision);
            Vector3 nextPoint = new Vector3(lastColPoint.x, 0, (pos.z - (lastColPoint.z - pos.z)));
            MoveDir = (nextPoint - pos).normalized;
            lastColPoint = pos;
        }
    }

    // 得到球跟墙或者是玩家的碰撞点
    Vector3 GetColliderPoint(Collision collision)
    {
        // 得到碰撞点
        ContactPoint contact = collision.contacts[0];
        Quaternion rot = Quaternion.FromToRotation(Vector3.up, contact.normal);
        // 得到球跟墙或者是玩家的碰撞点
        Vector3 ColliderPoint = contact.point;
        return ColliderPoint;
    }

    // 初始的时候得到一个随机的移动方向
    void GetMoveDir()
    {
        int randomXNum = Random.Range(1, 3);
       // Debug.Log("randomNum--->" + randomXNum);
        float x = 0;
        switch (randomXNum)
        {
            case 1:
                x = Random.Range(1f, 3f);
                break;
            case 2:
                x = Random.Range(-1f, -3f);
                break;
            default:
                break;
        }
        int randomZNum = Random.Range(1, 3);
       // Debug.Log("randomNum--->" + randomZNum);
        float z = 0;
        switch (randomZNum)
        {
            case 1:
                z = Random.Range(1f, 2f);
                break;
            case 2:
                z = Random.Range(-1f, -2f);
                break;
            default:
                break;
        }
        MoveDir = new Vector3(x, 0, z);
        Debug.Log("初始方向" + MoveDir);
    }
    #endregion

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值