Unity3D键盘+鼠标漫游脚本

两个代码都附在MainCamera上面,可以实现键盘加鼠标漫游


1、KeyMove.cs  键盘漫游

using UnityEngine;
using System.Collections;

public class KeyMove : MonoBehaviour {

	void Start () {

	}
	void Update () {
		//前后左右
		if (Input.GetKey (KeyCode.A)) {
			transform.Translate (-25 * Time.deltaTime,0, 0 , Space.Self);
		}
		if (Input.GetKey (KeyCode.D)) {
			transform.Translate ( 25 * Time.deltaTime,0, 0 , Space.Self);
		}
		if (Input.GetKey (KeyCode.W)) {
			transform.Translate (0, 0, 25 * Time.deltaTime, Space.Self);
		}
		if (Input.GetKey (KeyCode.S)) {
			transform.Translate (0, 0 , -25 * Time.deltaTime,Space.Self);
		}
		//旋转
		if (Input.GetKey (KeyCode.Q)) {
			transform.Rotate (0, -25 * Time.deltaTime, 0, Space.Self);
		}
		if (Input.GetKey (KeyCode.E)) {
			transform.Rotate (0, 25 * Time.deltaTime, 0, Space.Self);
		}
		if (Input.GetKey (KeyCode.Z)) {
			transform.Rotate (-25 * Time.deltaTime,0, 0 , Space.Self);
		}
		if (Input.GetKey (KeyCode.C)) {
			transform.Rotate ( 25 * Time.deltaTime,0, 0 , Space.Self);
		}
		//升高降低镜头
		if (Input.GetKey (KeyCode.H)) {
			transform.Translate (0, 5 * Time.deltaTime, 0);
		}
		if (Input.GetKey (KeyCode.N)) {
			transform.Translate (0, -5 * Time.deltaTime, 0);
		}
	}
}

2、【转发】鼠标漫游

using UnityEngine;
using System.Collections;

public class FlyMove : MonoBehaviour {
	private float sensitivityX = 1F;		//X转动增量速度
	private float sensitivityY = 1F;		//y转动增量速度
	private float minimumY = -90F;			//Y轴转动限制
	private float maximumY = 90F;
	float rotationY = 0F;					//y起始值
	private float MovingSpeed = 1f;			//移动屏幕的速度
	float delta_x,delta_y,delta_z;			//计算移动量
	float distance = 5;						
	float ZoomSpeed = 20f;					//拉近拉远速度
	Quaternion rotation;

	void Start () {

	}

	void Update () {
		if(Input.GetMouseButton(0)){//左键旋转屏幕
			{
				float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;

				rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
				rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);

				transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
			}

		}
		if (Input.GetMouseButton(2)){

		}
		if(Input.GetAxis("Mouse ScrollWheel")!= 0){//滚轴拉近拉远
			delta_z = -Input.GetAxis("Mouse ScrollWheel") * ZoomSpeed;
			transform.Translate(0,0,-delta_z);
			distance += delta_z;
		}
		if (Input.GetMouseButton (2)) {//滚轴中间移动屏幕
			delta_x = Input.GetAxis("Mouse X") * MovingSpeed;
			delta_y = Input.GetAxis("Mouse Y") * MovingSpeed;
			rotation = Quaternion.Euler(0, transform.rotation.eulerAngles.y,0 );
			transform.position =rotation * new Vector3(-delta_x,-delta_y,0)+transform.position;
		}
	}
}




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值