以下是一个简单的TPS游戏源码示例:
复制插入
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f; // 玩家移动速度
public float rotateSpeed = 3f; // 玩家旋转速度
public GameObject bulletPrefab; // 子弹预制体
public Transform bulletSpawnPoint; // 子弹生成位置
public float bulletSpeed = 20f; // 子弹速度
public float fireRate = 0.2f; // 射击速率
private float nextFireTime = 0f; // 下次射击时间
private Animator animator;
private Rigidbody rigidbody;
void Start()
{
animator = GetComponent<Animator>();
rigidbody = GetComponent<Rigidbody>();
}
void Update()
{
// 获取玩家输入
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
// 计算移动向量
Vector3 moveDirection = new Vector3(h, 0, v);
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= moveSpeed;
// 更新玩家动画
animator.SetFloat("Speed", Mathf.Abs(v) + Mathf.Abs(h));
// 玩家移动
rigidbody.MovePosition(transform.position + moveDirection * Time.deltaTime);
// 玩家旋转
Ray cameraRay = Camera.main.ScreenPointToRay(Input.mousePosition);
Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
float rayLength;
if (groundPlane.Raycast(cameraRay, out rayLength))
{
Vector3 pointToLook = cameraRay.GetPoint(rayLength);
transform.LookAt(new Vector3(pointToLook.x, transform.position.y, pointToLook.z));
}
// 射击
if (Input.GetMouseButton(0) && Time.time > nextFireTime)
{
nextFireTime = Time.time + fireRate;
GameObject bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, Quaternion.identity);
bullet.GetComponent<Rigidbody>().velocity = transform.forward * bulletSpeed;
Destroy(bullet, 2f);
}
}
}
复制插入
此代码实现了玩家的移动、旋转和射击功能,其中使用了Unity的Animator组件控制玩家动画。可以在此基础上添加更多功能,如玩家和敌人的血量、碰撞检测、游戏关卡等,以实现一个完整的TPS游戏。