Unity中实现小球反弹
Posted Hello Bug.
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity中实现小球反弹相关的知识,希望对你有一定的参考价值。
一:演示视频
二:代码实现
using UnityEngine;
public class Player : MonoBehaviour
{
private void Update()
{
transform.Translate(transform.forward * Time.deltaTime * 30, Space.World);
}
private void OnCollisionEnter(Collision other)
{
if (other.gameObject.tag == "Up")
{
float rotateY = transform.rotation.eulerAngles.y;
float targetY = (90 - rotateY) + 90 - rotateY;
transform.Rotate(Vector3.up * targetY);
}
if (other.gameObject.tag == "Down")
{
float rotateY = transform.rotation.eulerAngles.y;
float targetY = (90 - rotateY) + 90 - rotateY;
transform.Rotate(Vector3.up * targetY);
}
if (other.gameObject.tag == "Right")
{
float rotateY = transform.rotation.eulerAngles.y;
float targetY = (90 - rotateY) + 270 - rotateY;
transform.Rotate(Vector3.up * targetY);
}
if (other.gameObject.tag == "Left")
{
float rotateY = transform.rotation.eulerAngles.y;
float targetY = (90 - rotateY) + 270 - rotateY;
transform.Rotate(Vector3.up * targetY);
}
}
}
以上是关于Unity中实现小球反弹的主要内容,如果未能解决你的问题,请参考以下文章
100个 Unity实用技能☀️ | 求反射向量的方法,让小球按照物理反射的角度反弹(出射角=入射角)