unity射击小游戏,第一人称摄像机实现
unity射击小游戏,第一人称摄像机实现
今天开始写一些unity的小教程,就以刚刚写的第一人称的射击小游戏作为案例。
先上效果图:


首先游戏物品也没有多少东西,就是地板,平行光,主摄像机。然后我们需要做一个子弹,这个子弹里面添加刚体。然后把它作为预设体保存。
生成fire.cs文件。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class fire : MonoBehaviour
{public int speed =5;public GameObject newObject; // Start is called before the first frame updatevoid Start(){}// Update is called once per framevoid Update(){float z= Input.GetAxis("Vertical") * speed*Time.deltaTime;float x= Input.GetAxis("Horizontal") * speed *Time.deltaTime;transform.Translate(x, 0, z);if(Input.GetButtonDown("Fire1")){GameObject n = Instantiate(newObject,transform.position,transform.rotation);Vector3 fwd;fwd = transform.TransformDirection(Vector3.forward);n.GetComponent<Rigidbody>().AddForce(fwd*6000);Destroy(n, 5);}if (Input.GetKey(KeyCode.Q)){transform.Rotate(0, -50 * Time.deltaTime, 0);}if (Input.GetKey(KeyCode.E)){transform.Rotate(0, 50 * Time.deltaTime, 0);}if (Input.GetKey(KeyCode.Z)){transform.Rotate(-50 * Time.deltaTime, 0, 0);}if (Input.GetKey(KeyCode.C)){transform.Rotate(50 * Time.deltaTime, 0, 0);}}
}
这份代码直接挂在摄像机上面。newObject就是放入刚刚保存的预设体子弹就行了。
代码解析:
float z= Input.GetAxis("Vertical") * speed*Time.deltaTime;float x= Input.GetAxis("Horizontal") * speed *Time.deltaTime;
这里是管摄像头,也就是第一人称上下左右移动的。
if(Input.GetButtonDown("Fire1")){GameObject n = Instantiate(newObject,transform.position,transform.rotation);Vector3 fwd;fwd = transform.TransformDirection(Vector3.forward);n.GetComponent<Rigidbody>().AddForce(fwd*6000);Destroy(n, 5);}
这里管开火键,也就是鼠标左键。
仔细看这里的代码。这是预设体生成,也就是你们想要用代码动态生成物品,就要学习这部分代码。并且生成的子弹添加了一个向前的力,让它飞出去。
if (Input.GetKey(KeyCode.Q)){transform.Rotate(0, -50 * Time.deltaTime, 0);}
剩下这部分代码也就是管键盘事件。键盘按键输入,然后控制摄像机旋转,达到镜头左右上下转动的效果。
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
