当前位置: 首页 > article >正文

Unity方向键控制物体移动与跳跃

功能描述

    实现使用方向键控制物体在平面上移动,并使用空格键实现跳跃。

实现步骤

    添加3D物体:在场景中创建一个3D物体,作为跟随鼠标移动的物体。

    创建地面物体:在场景中创建一个平面(Plane),作为指定的地面物体,并为其设置一个Tag(例如Ground)。

    脚本代码:

using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float moveSpeed = 5f; // 移动速度
    public float jumpForce = 5f; // 跳跃力度
    private bool isGrounded; // 是否在地面上

    private Rigidbody rb;
     
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        // 获取输入
        float moveHorizontal = Input.GetAxisRaw("Horizontal"); // 使用 GetAxisRaw
        float moveVertical = Input.GetAxisRaw("Vertical");     // 使用 GetAxisRaw
        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical).normalized;

        // 移动
        rb.velocity = new Vector3(movement.x * moveSpeed, rb.velocity.y, movement.z * moveSpeed);
    }

    // Update is called once per frame
    void Update()
    {
        // 跳跃
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
        {
            rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
            isGrounded = false;
        }
    }

    void OnCollisionEnter(Collision collision)
    {
        // 检测是否在地面上
        if (collision.gameObject.CompareTag("Ground"))
        {
            isGrounded = true;
        }
    }

}

    应用到物体:

  • 将该脚本附加到你想要控制的物体上(例如一个立方体或角色模型)。

  • 确保该物体有一个Rigidbody组件,以便应用物理效果。

    调整参数:在Inspector窗口中,可以调整moveSpeedjumpForce的值,以控制移动速度和跳跃高度

注意事项:
  • 确保物体的Rigidbody组件没有勾选Is Kinematic,否则物理效果将不会生效。

  • 如果物体在移动时滑动过多,可以调整RigidbodyDrag值来增加阻力。

通过以上步骤,实现了使用方向键控制物体在Ground平面上移动,并使用空格键实现跳跃。


http://www.kler.cn/a/571630.html

相关文章:

  • 网络安全域的划分与隔离
  • 【文献阅读】ViNT: A Foundation Model for Visual Navigation
  • 智能设备上的 AI 移植与部署:新趋势与实践案例
  • uniapp 解决 H5 跨域问题
  • 基于Swintransformer与对称性损失函数的3D人体姿态估计
  • 论文插图绘制|R语言绘制瀑布图,展示高频突变基因在样本中的分布模式|25-03-04
  • 自动化学习-使用git进行版本管理
  • php的笔记(更新中)
  • 电子电气架构 --- 拓扑架构集中的趋势及其演变
  • RK3568平台(网络篇)RTL8111网卡
  • 【Elasticsearch】修改数据流(Data Stream)
  • 蓝桥云客 跑步
  • AI编程,常见的AI编程工具有哪些?如何用AI编程做一个简单的小软件?
  • Pycharm配置ROS开发环境
  • CSS_复合选择器
  • 【前沿 热点 顶会】CVPR 2025 录用的与图像|视频恢复、抠图、超分辨率、3D生成有关的论文
  • c++ cout详解
  • 【每日八股】MySQL篇(七):日志(上)
  • flink和yarn和mpp架构区别
  • Vue 调用摄像头扫描条码