Method1:利用ASDW控制角色移动,空格跳起。
- 创建地形。
- 添加一个空的GameObject,命名改为player。再添加一个Cube和Camera作为其子物体。
- Cube中打开Mesh Renderer。
- plyer上添加Character control组件,编写脚本playermove。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 人物移动的脚本,挂载到player上
/// </summary>
public class playermove : MonoBehaviour
{
// Start is called before the first frame update
public float speed;//设定移动速度
public float jumpspeed = 5;//跳跃速度
public float g = 15;//定义重力
public CharacterController playercontroller;
Vector3 move;//用来控制角色的三维方向运动
// Update is called once per frame
void Update()
{
float x=0, z=0;
if (playercontroller.isGrounded)//如果player在地上
{
x = Input.GetAxis("Horizontal");//获得水平和垂直两个坐标
z = Input.GetAxis("Vertical");//默认上下左右移动
move = (transform.right * x + transform.forward * z)*speed;
if (Input.GetAxis("Jump") == 1)//判断是否按下空格
{
move.y = jumpspeed;
}
}
move.y = move.y - g * Time.deltaTime;
playercontroller.Move(move*Time.deltaTime);//daltatime使速度和帧数相同
}
}
- 添加相机控制脚本。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cameracontrol : MonoBehaviour
{
public float mousespeed;
public Transform player;
private float xmove;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;//锁定鼠标,不能乱跑
}
// Update is called once per frame
void Update()
{
float x, y;
x = Input.GetAxis("Mouse X")*mousespeed*Time.deltaTime;//鼠标的x位置
y = Input.GetAxis("Mouse Y") * mousespeed * Time.deltaTime;//鼠标的y位置
xmove =xmove -y;
//限制镜头旋转角度
xmove = Mathf.Clamp(xmove,-90, 45);//第二个为抬头角度,第二个为低头角度
this.transform.localRotation = Quaternion.Euler(xmove, 0, 0);
player.Rotate(Vector3.up*x);//相机随着鼠标绕z轴旋转
}
}