给目标物体添加前后移动,左右旋转,向上跳跃功能

跳跃涉及到碰撞,新建地面-plane,勾选Mesh Collider下的convex,不勾Is Trigger; 新建cube,cube必须有(box collider)添加Rigidbody组件,勾选 Use Gravity,接下来就是敲击代码--

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

public class DingControler : MonoBehaviour
{
    //定义刚体变量和目标物体
    public Rigidbody 碰撞体;
    public Transform CUBE;
    //定义力的量
    public float Force;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        //按键方向操作  (使用input.getkey获取键盘映射) 前进
        if (Input.GetKey(KeyCode.W))
        {
            CUBE.Translate(Vector3.forward * 0.2f);
        }
        if (Input.GetKey(KeyCode.S))
        {
            CUBE.Translate(Vector3.back * 0.2f);
        }

        //旋转
        if (Input.GetKey(KeyCode.A))
        {
            CUBE.Rotate(Vector3.up, -5);
        }
        if (Input.GetKey(KeyCode.D))
        {
            CUBE.Rotate(Vector3.up, 5);
        }

        // 给碰撞体添加力 & 按空格键跳跃
        if (Input.GetKey(KeyCode.Space))
        {
            碰撞体.AddForce(碰撞体.transform.up * Force);
        }


    }
}

挂于目标体上,并设置力 force 的大小,比重力大,不要打太多(无所谓,自己调节改动着玩吧)

猜你喜欢

转载自blog.csdn.net/weixin_64625272/article/details/122506593
今日推荐