可以使用Unity的Input类来处理触摸屏幕的输入,并根据触摸的位置来确定子弹发射的方向。以下是一个示例代码,展示如何实现这个功能:
using UnityEngine;
public class ShootController : MonoBehaviour
{
public GameObject bulletPrefab; // 子弹预制体
void Update()
{
if (Input.touchCount > 0) // 检测是否有触摸输入
{
Touch touch = Input.GetTouch(0); // 获取第一个触摸点
if (touch.phase == TouchPhase.Began) // 触摸开始阶段
{
Vector2 touchPosition = touch.position; // 触摸点的屏幕坐标
Vector3 worldPosition = Camera.main.ScreenToWorldPoint(touchPosition); // 将屏幕坐标转换为世界坐标
// 计算子弹发射方向
Vector3 direction = (worldPosition - transform.position).normalized;
// 在固定方向发射子弹
GameObject bullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity);
bullet.GetComponent<Rigidbody>().velocity = direction * 10f; // 设置子弹速度
}
}
}
}
在上述代码中,我们首先检测触摸输入是否存在。如果存在,我们获取第一个触摸点的位置,并将其转换为世界坐标。然后,我们计算子弹发射的方向,即从玩家位置指向触摸位置的向量,并将其标准化。最后,我们在固定方向上发射子弹,使用Instantiate函数实例化子弹预制体,并将速度设置为方向乘以一个固定值。
子弹反射
//将角度制转换为弧度制
float Angle_Z = transform.rotation.eulerAngles.z * Mathf.Deg2Rad;
//拿到旋转向量,以便之后进行反射计算
Vector2 Direction = new Vector2(Mathf.Cos(Angle_Z), Mathf.Sin(Angle_Z));
//做反射运算,得到反射后的选择向量
Vector2 Out_Direction = Vector2.Reflect(Direction, collision.GetContact(0).normal);
//向旋转向量转为弧度制
Angle_Z = Mathf.Atan2(Out_Direction.y, Out_Direction.x);
//重新转换回角度制,并修改子弹角度,达成反射效果
transform.rotation = Quaternion.Euler(0, 0, Angle_Z * Mathf.Rad2Deg);