unity相机自由移动

unity相机实现自由移动

分享一下项目中的的相机移动代码。记录学习过程,其中有参考别人的代码,代码可以直接使用需,挂在需要移动的相机上。

using UnityEngine;
using System.Collections;

public class CameraFlyController : MonoBehaviour
{
	private float speed = 4f;
	
	private Transform tr;
	
	private Vector3 mpStart;
	private Vector3 originalRotation;

	private float t = 0f;
	
	// 
	void Awake()
	{
		tr = GetComponent<Transform>();
		t = Time.realtimeSinceStartup;
	}
	
	// 
	void Update()
	{
		// Movement
		float forward = 0f;
		if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow)) { forward += 1f; }
		if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow)) { forward -= 1f; }
		
		float right = 0f;
		if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow)) { right += 1f; }
		if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow)) { right -= 1f; }
		
		float up = 0f;
		if (Input.GetKey(KeyCode.E) || Input.GetKey(KeyCode.Space)) { up += 1f; }
		if (Input.GetKey(KeyCode.Q) || Input.GetKey(KeyCode.C)) { up -= 1f; }

		float dT = Time.realtimeSinceStartup - t;
		t = Time.realtimeSinceStartup;

		tr.position += tr.TransformDirection(new Vector3(right, up, forward) * speed * (Input.GetKey(KeyCode.LeftShift) ? 2f : 1f) * dT);
		
		// Rotation
		Vector3 mpEnd = Input.mousePosition;
		
		// Right Mouse Button Down
		if (Input.GetMouseButtonDown(1))
		{
			originalRotation = tr.localEulerAngles;
			mpStart = mpEnd;
		}
		
		// Right Mouse Button Hold
		if (Input.GetMouseButton(1))
		{
			Vector2 offs = new Vector2((mpEnd.x - mpStart.x) / Screen.width, (mpStart.y - mpEnd.y) / Screen.height);
			tr.localEulerAngles = originalRotation + new Vector3(offs.y * 360f, offs.x * 360f, 0f);
		}
	}
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值