这篇文章主要为大家详细介绍了Unity3D实现控制摄像机移动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了Unity3D实现控制摄像机移动的具体代码,供大家参考,具体内容如下
最近公司的几个项目开发内容基本相同,很多脚本直接复制过来就可以拼接项目。之前一直是代码爱好者,能自己敲的绝对不去复制粘贴。但是开发速度确实是被耽误了,所以接下来打算把开发中常用的脚本都发到博客上。自己需要的时候直接拿来。也希望能帮到你们。
unity编辑器中按住鼠标右键,在通过控制键盘的wasdqe键可以自由控制视野。
下面就是实现操作的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//巡游模式摄像机控制
public class CameraMove : MonoBehaviour
{
public static CameraMove Instance = null;
private Vector3 dirVector3;
private Vector3 rotaVector3;
private float paramater = 0.1f;
//旋转参数
private float xspeed = -0.05f;
private float yspeed = 0.1f;
private float dis;
void Awake ()
{
Instance = this;
}
private void Start()
{
rotaVector3 = transform.localEulerAngles;
dis = UIFuc.Instance.Dis;
}
// Update is called once per frame
void FixedUpdate ()
{
//旋转
if (Input.GetMouseButton(1))
{
rotaVector3.y += Input.GetAxis("Horizontal") * yspeed;
rotaVector3.x += Input.GetAxis("Vertical") * xspeed;
transform.rotation = Quaternion.Euler(rotaVector3);
}
//移动
dirVector3 =Vector3.zero;
if (Input.GetKey(KeyCode.W))
{
if(Input.GetKey(KeyCode.LeftShift)) dirVector3.z = 3;
else dirVector3.z = 1;
}
if (Input.GetKey(KeyCode.S))
{
if (Input.GetKey(KeyCode.LeftShift)) dirVector3.z = -3;
else dirVector3.z = -1;
}
if (Input.GetKey(KeyCode.A))
{
if (Input.GetKey(KeyCode.LeftShift)) dirVector3.x = -3;
else dirVector3.x = -1;
}
if (Input.GetKey(KeyCode.D))
{
if (Input.GetKey(KeyCode.LeftShift)) dirVector3.x = 3;
else dirVector3.x = 1;
}
if (Input.GetKey(KeyCode.Q))
{
if (Input.GetKey(KeyCode.LeftShift)) dirVector3.y = -3;
else dirVector3.y = -1;
}
if (Input.GetKey(KeyCode.E))
{
if (Input.GetKey(KeyCode.LeftShift)) dirVector3.y = 3;
else dirVector3.y = 1;
}
transform.Translate(dirVector3 * paramater,Space.Self);
//限制摄像机范围
transform.position = Vector3.ClampMagnitude(transform.position, dis);
}
}
由于项目需要限制摄像机的移动范围,所以我在最后加上了限制的代码。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
织梦狗教程
本文标题为:Unity3D实现控制摄像机移动


基础教程推荐
猜你喜欢
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- C# 解析XML和反序列化的示例 2023-04-14
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- C#中的Linq to JSON操作详解 2023-06-08
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- Unity shader实现高斯模糊效果 2023-01-16
- C#中 Json 序列化去掉null值的方法 2022-11-18