unity入门(用unity3d写一个简单的tps移动+射击引擎)

以下是一个简单的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游戏。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值