Unity2D实现拖拽发射小球碰撞预制体时随机改变方向的问题
实现碰撞指定预制体随机转向的方案
步骤1:修改Player脚本,新增随机转向逻辑
在原有Player类中新增随机转向相关字段和方法,修改后完整代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { [SerializeField] private float power = 2; [SerializeField] private Vector2 minPow, maxPow; [SerializeField] private float randomTurnRange = 90f; // 新增:随机转向的角度范围(正负区间) public Vector3 force; private Vector3 startPoint, endPoint; private Rigidbody2D rb; private Camera cam; private Aim aim; void Start() { cam = Camera.main; rb = GetComponent<Rigidbody2D>(); aim = GetComponent<Aim>(); } void Update() { if(Input.GetMouseButtonDown(0)) { startPoint = cam.ScreenToWorldPoint(Input.mousePosition); startPoint.z = 15; } if(Input.GetMouseButton(0)) { Vector3 currentPos = cam.ScreenToWorldPoint(Input.mousePosition); startPoint.z = 15; aim.RenderLine(startPoint, currentPos); } if(Input.GetMouseButtonUp(0)) { endPoint = cam.ScreenToWorldPoint(Input.mousePosition); endPoint.z = 15; force = new Vector3(Mathf.Clamp(startPoint.x - endPoint.x, minPow.x, maxPow.x), Mathf.Clamp(startPoint.y - endPoint.y, minPow.y, maxPow.y)); rb.AddForce(force * power, ForceMode2D.Impulse); aim.EndLine(); } } public void BoostUp(float pow) { rb.velocity *= pow; } // 新增:随机转向方法 public void RandomTurn() { // 小球静止时不触发转向 if (rb.velocity.magnitude < 0.1f) return; // 计算当前速度对应的角度 float currentAngle = Mathf.Atan2(rb.velocity.y, rb.velocity.x) * Mathf.Rad2Deg; // 叠加随机角度偏移 float newAngle = currentAngle + Random.Range(-randomTurnRange, randomTurnRange); // 转换为新的方向向量 float newAngleRad = newAngle * Mathf.Deg2Rad; Vector2 newDirection = new Vector2(Mathf.Cos(newAngleRad), Mathf.Sin(newAngleRad)); // 保持原有速度大小,应用新方向 rb.velocity = newDirection * rb.velocity.magnitude; } }
步骤2:创建触发转向的预制体脚本
新建RandomTurnTrigger脚本,挂载到需要触发随机转向的指定预制体上:
using UnityEngine; public class RandomTurnTrigger : MonoBehaviour { private void OnTriggerEnter2D(Collider2D other) { if(other.CompareTag("Player")) { Player player = other.GetComponent<Player>(); if(player != null) { player.RandomTurn(); // 若需要碰撞后销毁该预制体,取消注释下一行即可 // Destroy(gameObject); } } } }
配置说明
- 触发转向的预制体需要添加2D碰撞体组件,勾选
Is Trigger属性 - 可在Inspector面板调整Player脚本的
randomTurnRange参数:设置为180则完全随机转向,设置为30则最多偏离当前运动方向30度 - 如果预制体不需要走触发逻辑,而是实体碰撞效果,将
OnTriggerEnter2D替换为OnCollisionEnter2D,参数修改为Collision2D other,判断条件改为other.collider.CompareTag("Player")即可
内容的提问来源于stack exchange,提问作者Hisoka
相关产品推荐
相关产品推荐

