unity第一人称漫游脚本(不断更新)

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使速度和帧数相同
    }
}

player的属性

  • 添加相机控制脚本。
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轴旋转



    }
}
  • 10
    点赞
  • 77
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值