您的位置:首页 > 移动开发 > Unity3D

使用unity3d搭建简单的场景以及第一人称角色的控制

2017-07-07 15:49 351 查看

一、搭建简单的游戏场景

1、打开unity3d编辑器,新建一个空工程。
2、创建若干个cube对象,通过伸缩变换形成地板,墙壁以及障碍物等。
3、创建平行灯,照亮场景
4、创建一个胶囊对象,作为角色
5、在胶囊对象上添加摄像机,作为角色的眼睛,摄像机的摄像范围极为角色的视野。

创建好的场景图如下:



二、通过鼠标的移动控制角色的视野

新建脚本MouseLook.cs,编辑控制代码,并将脚本组件添加到角色对象上。代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MouseLook : MonoBehaviour {

public enum RotationAxes
{
MouseXAndY = 0,
MouseX = 1,
MouseY = 2
}

public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityHor = 9.0f;
public float sensitivityVert = 9.0f;

public float minimumVert = -15.0f;
public float maximumVert = 45.0f;

private float _rotationX = 0;

// Use this for initialization
void Start () {
Rigidbody body = GetComponent<Rigidbody>();
if(body != null)
{
body.freezeRotation = true;
}
}

// Update is called once per frame
void Update () {
if(axes == RotationAxes.MouseX)
{
//horizontal rotation here
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityHor, 0);
}
else if(axes == RotationAxes.MouseY)
{
//vertical rotation here
_rotationX -= Input.GetAxis("Mouse Y") * sensitivityVert;
_rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);
float rotationY = transform.localEulerAngles.y;
transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0);
}
else
{
//both horizontal and vertical rotation here
_rotationX -= Input.GetAxis("Mouse Y") * sensitivityVert;
_rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);
float delta = Input.GetAxis("Mouse X") * sensitivityHor;
float rotationY = transform.localEulerAngles.y + delta;
transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0);
}
}
}

三、通过键盘控制角色移动

新建脚本KeyboardMove.cs,编辑代码,并将该脚本组件添加到角色对象中。代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(CharacterController))]
[AddComponentMenu("Control Script/FPS Input")]
public class KeyboardMove : MonoBehaviour {

public float speed = 6.0f;
public float gravity = 0;
private CharacterController _charController;     //用于引用CharacterController的变量

// Use this for initialization
void Start () {
_charController = GetComponent<CharacterController>();  //使用附加到相同对象上的其他组件
}

// Update is called once per frame
void Update () {
float deltaX = Input.GetAxis("Horizontal") * speed;
float deltaZ = Input.GetAxis("Vertical") * speed;
Vector3 movement = new Vector3(deltaX, 0, deltaZ);
movement = Vector3.ClampMagnitude(movement, speed); //将对角移动的速度限制为和沿着轴移动的速度一样
movement.y = gravity;
movement *= Time.deltaTime;
movement = transform.TransformDirection(movement);  //把movement向量从本地变换为全局坐标
_charController.Move(movement);  //告知CharacterController通过movement向量移动
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐