unity FPS游戏开发#1实现人物移动

该代码示例展示了在Unity中如何通过CharacterController组件控制物体移动,利用Input.GetAxis获取水平和垂直轴输入,结合transform.right和transform.forward计算移动方向,使用WASD键进行操控,并实现了物体爬坡功能。
摘要由CSDN通过智能技术生成

代码如下:

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

public class MoveBody : MonoBehaviour
{
    // Start is called before the first frame update
    public float speed_walk = 10f;//走路速度
    public Vector3 move_direction;//人物移动方向
    public CharacterController character_control;
    public bool isWalk;//用来判断是否在走路
    void Start()
    {
        
        character_control = this.GetComponent<CharacterController>();//获取CharacterController组件
    }

    // Update is called once per frame
    void Update()
    {
        move();//前后左右
    }
void move()
    {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        move_direction = transform.right * h + transform.forward * v;//移动的方向
        //Debug.Log(move_direction * speed_walk * Time.deltaTime);
if(move_direction * speed_walk * Time.deltaTime != Vector3.zero)
        {
            isWalk = true;
        }
        else
        {
            isWalk = false;
        }
        character_control.Move(move_direction * speed_walk * Time.deltaTime);//移动
    }

通过CharacterController组件来控制物体移动,

float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        move_direction = transform.right * h + transform.forward * v;//移动的方向

这三行代码用于获取物体移动方向,move_direction是一个三维向量,默认是0向量,物体移动就会变为非零向量。

最后就用character_control.Move(move_direction * speed_walk * Time.deltaTime);来移动物体啦

这种方法可以实现物体爬坡,用WASD操控物体移动即可。

后期教程将逐步完善代码。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值