当前位置:主页 > 查看内容

unity射击小游戏,第一人称摄像机实现

发布时间:2021-07-18 00:00| 位朋友查看

简介:unity射击小游戏第一人称摄像机实现 今天开始写一些unity的小教程就以刚刚写的第一人称的射击小游戏作为案例。 先上效果图 首先游戏物品也没有多少东西就是地板平行光主摄像机。然后我们需要做一个子弹这个子弹里面添加刚体。然后把它作为预设体保存。 生成f……

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 update
    void Start()
    {
        
    }

    // Update is called once per frame
    void 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);
            
        }

剩下这部分代码也就是管键盘事件。键盘按键输入,然后控制摄像机旋转,达到镜头左右上下转动的效果。

;原文链接:https://blog.csdn.net/weixin_57171554/article/details/115750151
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文


随机推荐