其他分享
首页 > 其他分享> > Unity第一人称角色控制器(可直接拿来主义)

Unity第一人称角色控制器(可直接拿来主义)

作者:互联网

创建一个player(胶囊),然后把camera挂在player身上

public class 给摄像机的脚本 : MonoBehaviour
{
private float xMouse, yMouse;//获取鼠标转动的值
public float mouseSpeed=30;//鼠标灵敏度
public GameObject player;//获取player

private float xRotate;//用来接收yMouse的值
void Start()
{
    
}

void Update()
{
    xMouse = Input.GetAxis("Mouse X") * mouseSpeed * Time.deltaTime;
    yMouse = Input.GetAxis("Mouse Y") * mouseSpeed * Time.deltaTime;
    xRotate -= yMouse;//赋值
    xRotate = Mathf.Clamp(xRotate,-70,70);//限制旋转(上下看)的值
    transform.localRotation = Quaternion.Euler(xRotate,0,0);//上下看(沿着rigiht轴旋转)
    player.transform.Rotate(Vector3.up,xMouse);//左右旋转

    
}

}

public class 给player的脚本: MonoBehaviour
{
private CharacterController cc;

public float moveSpeed=50;//移动速度
public float jumpSpeed=10;//跳跃速度

private float horizontalMove, verticalMove;//定义获得按键值的两个变量
private Vector3 dir;//定义三维变量控制方向

public float gravity;//重力
private Vector3 velocity;//用来控制y轴加速度


public Transform groundCheck;//检测半径的位置
public float checkRadius;//检测球面的半径
public LayerMask groundLayer;//检测的层级
public bool isGround;//用来存储是否碰撞到地面

public int jumpDegree;
void Start()
{
    cc = GetComponent<CharacterController>();//获得controller组件
}

void Update()
{

    if (Input.GetKeyDown(KeyCode.LeftShift))
    {
        moveSpeed *= 2;
    }
    if (Input.GetKeyUp(KeyCode.LeftShift))
    {
        moveSpeed /= 2;
    }

    isGround = Physics.CheckSphere(groundCheck.position,checkRadius,groundLayer);//射线检测(发射射线检测的位置,检测球面的半径,检测的层级)
    if (isGround&&velocity.y<0)//如果碰撞到地面
    {
        velocity.y = -0.5f;
        jumpDegree = 0;
    }
    if (Input.GetButtonDown("Jump") && jumpDegree < 2)
    {
        velocity.y = jumpSpeed;
        jumpDegree++;
    }

    horizontalMove = Input.GetAxis("Horizontal")*moveSpeed;
    verticalMove = Input.GetAxis("Vertical")*moveSpeed;
    dir = transform.forward * verticalMove + transform.right * horizontalMove;//将按键的值赋值给三维变量
    cc.Move(dir*Time.deltaTime);//用move方法(三维变量*时间速率),,,注:这里的三维变量里面传递的值没有y轴

    velocity.y -= gravity * Time.deltaTime;//每秒就会减去重力的值不断下降(增加重力)
    cc.Move(velocity*Time.deltaTime);//赋值给move方法


}

}

标签:检测,xRotate,float,private,player,Unity,拿来主义,第一人称,public
来源: https://blog.csdn.net/Dore__/article/details/109989160