2015-09-15 10:09:48 yangyisen0713 阅读数 25680

C#控制WASD键盘前后左右及空格键抬升高度脚本代码如下:

using UnityEngine;
using System.Collections;

public class CameraControl : MonoBehaviour {
	// Use this for initialization
	private GameObject gameObject;
	float x1;
	float x2;
	float x3;
	float x4;
	void Start () {
		gameObject = GameObject.Find ("Main Camera");
	}
	
	// Update is called once per frame
	void Update () {
		//空格键抬升高度
		if (Input.GetKey (KeyCode.Space))
		{
			transform.position =  new Vector3(transform.position.x,transform.position.y + 1,transform.position.z);
		}	 

		//w键前进
		if(Input.GetKey(KeyCode.W))
		{
			this.gameObject.transform.Translate(new Vector3(0,0,50*Time.deltaTime));
		}
		//s键后退
		if(Input.GetKey(KeyCode.S))
		{
			this.gameObject.transform.Translate(new Vector3(0,0,-50*Time.deltaTime));
		}
		//a键后退
		if(Input.GetKey(KeyCode.A))
		{
			this.gameObject.transform.Translate(new Vector3(-10,0,0*Time.deltaTime));
		}
		//d键后退
		if(Input.GetKey(KeyCode.D))
		{
			this.gameObject.transform.Translate(new Vector3(10,0,0*Time.deltaTime));
		}
	}
}

JS控制鼠标移动视角代码如下:

using UnityEngine;
using System.Collections;


[AddComponentMenu("Camera-Control/Mouse Look")]
public class MouseLook : MonoBehaviour {

	public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
	public RotationAxes axes = RotationAxes.MouseXAndY;
	public float sensitivityX = 15F;
	public float sensitivityY = 15F;

	public float minimumX = -360F;
	public float maximumX = 360F;

	public float minimumY = -60F;
	public float maximumY = 60F;

	float rotationY = 0F;

	void Update ()
	{
		if (axes == RotationAxes.MouseXAndY)
		{
			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);
		}
		else if (axes == RotationAxes.MouseX)
		{
			transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
		}
		else
		{
			rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
			rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
			
			transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0);
		}
	}
	
	void Start ()
	{
		// Make the rigid body not change rotation
		if (GetComponent<Rigidbody>())
			GetComponent<Rigidbody>().freezeRotation = true;
	}
}

2017-05-02 16:38:03 yongh701 阅读数 24219

在3D游戏里面,视角是一个很重要的因素,部分玩家对锁视角嗤之以鼻,因此视角也是游戏制作里面需要努力的方面。其实也不难,换到Unity3D里面是想办法控制摄像机的移动。下面举一个简单的例子说明在Unity3D如何用键盘鼠标控制视角的移动的。如下图所示:


就像大部分游戏一样,可以用鼠标滚轮控制视角的远近,键盘的wasd和上下左右控制镜头的位置,而按着鼠标右键则可以控制镜头的旋转。当然你可以根据需要改成其它控制方式,反正原理是同一个原理。

其实这个游戏场景布置非常非常简单,也不是本文的重点。如下图所示,基本能够一览无遗:


如上图所示,我们其实需要做的,只是控制Main Camera的位置和旋转则能够做到上面的效果。因此赋予给Main Camera,如下的脚本CameraMove.cs:

using UnityEngine;
using System.Collections;

public class CameraMove : MonoBehaviour
{
    public float sensitivityMouse = 2f;
    public float sensitivetyKeyBoard = 0.1f;
    public float sensitivetyMouseWheel = 10f;

    void Update()
    {
        //滚轮实现镜头缩进和拉远
        if (Input.GetAxis("Mouse ScrollWheel") != 0)
        {
            this.camera.fieldOfView = this.camera.fieldOfView - Input.GetAxis("Mouse ScrollWheel") * sensitivetyMouseWheel;
        }
        //按着鼠标右键实现视角转动
        if (Input.GetMouseButton(1))
        {
            transform.Rotate(-Input.GetAxis("Mouse Y") * sensitivityMouse, Input.GetAxis("Mouse X") * sensitivityMouse, 0);
        }

        //键盘按钮←/a和→/d实现视角水平移动,键盘按钮↑/w和↓/s实现视角水平旋转
        if (Input.GetAxis("Horizontal") != 0)
        {
            transform.Translate(Input.GetAxis("Horizontal") * sensitivetyKeyBoard, 0, 0);
        }
        if (Input.GetAxis("Vertical") != 0)
        {
            transform.Translate(0, Input.GetAxis("Vertical") * sensitivetyKeyBoard, 0);
        }
    }

}

鼠标右键点击的监听这里就不说了,在《【Unity3D】用鼠标点击事件、AddForce完成跳跃与二段跳》(点击打开链接)已经详细说过了。这里引用了Input.GetAxis的概念。理论上,你可以像《【Unity3D】利用物体碰撞检测、键盘输入处理完成平衡球游戏》(点击打开链接)那样控制物体移动那样,控制主摄像机的移动与旋转的,但是使用Input.GetAxis会让你代码更加简洁,在Unity3D中有18条轴,不过基本上常用轴就是上述代码的几个。

Input.GetAxis能够获取这个轴的输入,也就是同样是用来监听鼠标输入的一个东西,它将返回一个-1~1的数值。用于记录用户按键盘的时长、翻滚轮、鼠标对比上一个位置偏移的多少。这样的话,我们再乘上一个合适的float,则可以形成一个坐标位置。配合Rotate与Translate则能够时物体移动。

另一方面,摄像头的焦距,也就是缩放可以直接对fieldOfView控制而达成。

2015-02-01 07:00:20 hanghangaidoudou 阅读数 7225

鼠标控制:

using UnityEngine;
using System.Collections;


public class shubiao : MonoBehaviour {
//public Transform firepos;
public int Ball=30;
public int CurBall=1;
public Rigidbody projectile;
public Vector3 point;
public float time=100f;
public GameObject Juese;
public GameObject lumian;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
Juese=GameObject.Find ("shijue");
GameObject PengZhuang1=GameObject.Find ("PengZhuang1");
GameObject PengZhuang2=GameObject.Find ("PengZhuang2");
GameObject PengZhuang3=GameObject.Find ("PengZhuang3");
GameObject PengZhuang4=GameObject.Find ("PengZhuang4");
GameObject PengZhuang5=GameObject.Find ("PengZhuang5");
   GameObject PengZhuang6=GameObject.Find ("PengZhuang6");
if(Juese==null)
{


return;
}
if(Input.GetMouseButton(0))
{
Ray ray=Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast (ray,out hit))
{
if(hit.transform==Juese.transform)
{
print("命中了球");

}
if(hit.transform==PengZhuang1.transform)
{
print("碰撞了墙1");
return;
}
if(hit.transform==PengZhuang2.transform)
{
print("碰撞了墙2");
return;
}
if(hit.transform==PengZhuang3.transform)
{
print("碰撞了墙3");
return;
}
if(hit.transform==PengZhuang4.transform)
{
print("碰撞了墙4");
return;
}
if(hit.transform==PengZhuang5.transform)
{
print("碰撞了墙5");
return;
}
if(hit.transform==PengZhuang6.transform)
{
print("碰撞了墙6");
Application.LoadLevel(1);
return;
}
point=hit.point;
Juese.transform.LookAt(new Vector3(point.x,Juese.transform.position.y,point.z));
time=Time.realtimeSinceStartup;
Move(0.15f);


}
}
}
void Move(float speed)
{
if(Mathf.Abs (Vector3.Distance(point,transform.position))>=1.3f)
{

// Rigidbody clone2;
// clone2 = Instantiate(projectile, point, firepos.rotation) as Rigidbody;
// clone2.velocity = transform.TransformDirection(Vector3.forward * 10);
//transform.Translate(point);
Juese.transform.Translate(Vector3.forward* Time.deltaTime*20);
// transform.Translate (point* Time.deltaTime*20);
// print(point.x);
// print("forward"+Vector3.forward.x);
// CharacterController cctl= GetComponent<CharacterController>();
// Vector3 v=Vector3.ClampMagnitude(point,speed);
// cctl.Move(v);
}

}
void OnMouseDown()
{
Debug.Log("OnMouseDown");


}




}

键盘控制:

using UnityEngine;
using System.Collections;


public class shijue : MonoBehaviour {
//public GameObject ballgo;
// Use this for initialization
void Start () {

}
// Update is called once per frame
void Update () {

// ballgo=GameObject.Find ("zidan");
// if(Ball==null||firepos==null)
// return;
//// if (Input.GetButtonDown("Fire1")) {
//if (Input.GetKeyDown(KeyCode.Space))
//{
// Rigidbody clone1;
// clone1 = Instantiate(projectile, firepos.position, firepos.rotation) as Rigidbody;
// clone1.velocity = transform.TransformDirection(Vector3.forward * 120);
//}
if(Input.GetKey (KeyCode.W))
{
print("----------w"); 
transform.Translate (Vector3.forward * Time.deltaTime*60);
}
if(Input.GetKey (KeyCode.S))
{

print("---------------s");
transform.Translate (Vector3.forward * Time.deltaTime*-60);
}
if(Input.GetKey (KeyCode.A))
{
print("---a");
transform.Rotate(Vector3.up * Time.deltaTime*-60);
}
if(Input.GetKey (KeyCode.D))
{

print("------------d");
transform.Rotate(Vector3.up * Time.deltaTime*60);
}



}



}

2018-01-04 10:15:53 q764424567 阅读数 2749

Unity3d 鼠标和键盘控制摄像机的视角缩放与扩大、视角平移、视角旋转

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Mouse_Controller : MonoBehaviour
{
    public float xRoatationSpeed = 250.0f;
    public float yRoatationSpeed = 120.0f;

    public float moveSpeed = 800f;

    public float yRoatationMinLimit = -90f;
    public float yRoatationMaxLimit = 90f;

    public float ScaleSpeed = 300;

    public float KeyboardMoveSpeed = 10;
    public float DefaultKeyboardMoveSpeed = 10;
    public float KeyboardMoveAcceleratedSpeed = 3;

    public float MaxMoveDistance = 5000f;

    private KeyCode _forwardKey = KeyCode.W;

    public KeyCode ForwardKey
    {
        get { return _forwardKey; }
        set { _forwardKey = value; }
    }

    private KeyCode _backKey = KeyCode.S;

    public KeyCode BackKey
    {
        get { return _backKey; }
        set { _backKey = value; }
    }

    private KeyCode _leftKey = KeyCode.A;

    public KeyCode LeftKey
    {
        get { return _leftKey; }
        set { _leftKey = value; }
    }

    private KeyCode _rightKey = KeyCode.D;

    public KeyCode RightKey
    {
        get { return _rightKey; }
        set { _rightKey = value; }
    }
    private void Update()
    {
        Vector3 intos = gameObject.transform.position;
        if (intos.y<-5600)
        {
            moveSpeed = 80f;
            ScaleSpeed = 30f;
        }
        else if (intos.y >-5600)
        {
            moveSpeed = 800f;
            ScaleSpeed = 3000f;
        }
    }

    void Awake()
    {

    }

    void Start()
    {
    }

    void LateUpdate()
    {
        Vector3 oldPos = this.transform.position;

        //鼠标左键
        if (Input.GetMouseButton(0))
        {
            var position = transform.position;
            position += transform.TransformDirection(Vector3.left).normalized * (Input.GetAxis("Mouse X") * moveSpeed * 0.02f);
            position += transform.TransformDirection(Vector3.down).normalized * (Input.GetAxis("Mouse Y") * moveSpeed * 0.02f);

            movePosition(position);
        }

        ////鼠标右键
        //if (Input.GetMouseButton(1))
        //{
        //    float x = 0;
        //    float y = 0;

        //    x += Input.GetAxis("Mouse X") * xRoatationSpeed * 0.02f;
        //    y -= Input.GetAxis("Mouse Y") * yRoatationSpeed * 0.02f;

        //    y = ClampAngle(y, yRoatationMinLimit, yRoatationMaxLimit);

        //    transform.Rotate(y, x, 0);

        //    var angles = transform.eulerAngles;
        //    angles.z = 0;

        //    transform.eulerAngles = angles;
        //}

        //鼠标滑轮
        if (Input.GetAxis("Mouse ScrollWheel") != 0)
        {
            var moveDistance = Input.GetAxis("Mouse ScrollWheel") * ScaleSpeed;

            var position = transform.position;
            position += transform.TransformDirection(Vector3.forward).normalized * moveDistance;

            movePosition(position);
        }

        if (Input.GetKey(ForwardKey))
        {
            var position = transform.position;
            position += transform.TransformDirection(Vector3.forward).normalized * KeyboardMoveSpeed * 0.02f;

            movePosition(position);
        }

        if (Input.GetKey(BackKey))
        {
            var position = transform.position;
            position += transform.TransformDirection(Vector3.back).normalized * KeyboardMoveSpeed * 0.02f;

            movePosition(position);
        }

        if (Input.GetKey(LeftKey))
        {
            var position = transform.position;
            position += transform.TransformDirection(Vector3.left).normalized * KeyboardMoveSpeed * 0.02f;

            movePosition(position);
        }

        if (Input.GetKey(RightKey))
        {
            var position = transform.position;
            position += transform.TransformDirection(Vector3.right).normalized * KeyboardMoveSpeed * 0.02f;

            movePosition(position);
        }

        if (Input.GetKey(ForwardKey) || Input.GetKey(BackKey) || Input.GetKey(LeftKey) || Input.GetKey(RightKey))
        {
            KeyboardMoveSpeed += KeyboardMoveAcceleratedSpeed * 0.02f;
        }
        else
        {
            KeyboardMoveSpeed = DefaultKeyboardMoveSpeed;
        }

        if (Vector3.Distance(transform.position, Vector3.zero) > MaxMoveDistance)
        {
            movePosition(oldPos + oldPos.normalized * -100);
        }
    }

    void movePosition(Vector3 moveToPosition)
    {
        if (transform.GetComponent<Rigidbody>())
        {
            if (!Physics.Raycast(transform.position, moveToPosition - transform.position, (moveToPosition - transform.position).magnitude))
            {
                transform.GetComponent<Rigidbody>().MovePosition(moveToPosition);
            }
        }
    }

    float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360)
            angle += 360;
        if (angle > 360)
            angle -= 360;
        return Mathf.Clamp(angle, min, max);
    }
}

代码主要功能就是控制是摄像机的视角的缩放与扩大、视角平移、视角旋转
主要控制的代码:

void movePosition(Vector3 moveToPosition)
    {
        if (transform.GetComponent<Rigidbody>())
        {
            if (!Physics.Raycast(transform.position, moveToPosition - transform.position, (moveToPosition - transform.position).magnitude))
            {
                transform.GetComponent<Rigidbody>().MovePosition(moveToPosition);
            }
        }
    }

很明显是控制是摄像机的Rigidbody来实现移动的
所以在摄像机上不仅要加上上面这一段代码,而且还要加上Rigidbody组件才能有效果
然后代码的参数都可以修改
如果修改不了可以把下面的代码注释掉

private void Update()
{
Vector3 intos = gameObject.transform.position;
if (intos.y<-5600)
{
moveSpeed = 80f;
ScaleSpeed = 30f;
}
else if (intos.y >-5600)
{
moveSpeed = 800f;
ScaleSpeed = 3000f;
}
}

OK 感觉没有什么要注释的了
复用性很高 值得借鉴哦

2017-10-20 13:10:57 qq_33994566 阅读数 6472

最近公司的几个项目开发内容基本相同,很多脚本直接复制过来就可以拼接项目。之前一直是代码爱好者,能自己敲的绝对不去复制粘贴。但是开发速度确实是被耽误了,所以接下来打算把开发中常用的脚本都发到博客上。自己需要的时候直接拿来。也希望能帮到你们。

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);
    }
}


由于项目需要限制摄像机的移动范围,所以我在最后加上了限制的代码。

没有更多推荐了,返回首页