Unity3D学习 ① 创建一个可移动,跳跃的物体

1.创建一个地面(plane)

点击unity导航栏上的GameObeject,选择3D Obejct,再选择plane就可以创建一个地面。

2.创建一个立方体(cube)用来代替玩家(player)

2.1 创建立方体

点击unity导航栏上的GameObeject,选择3D Obejct,再选择cube就可以创建一个立方体。

 2.2  赋予立方体属性

赋予立方体刚体(rigidbody)属性,使得立方体具有重力、碰撞等一般物理特性。

点击Hierarchy中之前创建的cube,再点击inspector中的Add component 搜索 Rigidbody即可添加成功。

其默认有重力。

 

 2.3 通过脚本使得立方体移动

unity中控制物体移动的原理为通过代码(脚本),改变物体的Transform属性

Position代表物体的三维位置,Rotation代表物体的旋转角度,Scale代表物体的缩放程度

2.3.1 创建脚本文件

在Assets中新建一个文件夹Scripts。(在Assets中点击鼠标右键,点击create,再点击folder)

 在Scripts中点击鼠标右键,点击create,再点击C# Scripts

2.3.2 脚本文件实现

点击创建好的move文件。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// 注意此处Move需要与你的脚本名称对应
public class Move : MonoBehaviour
{
    // 控制物体的移动速度
    public float moveSpeed = 5f;
    Vector3 moveAmount;
    // 刚体属性
    Rigidbody rb;
    // 在开始的一帧执行的函数
    void Start()
    {
        // 获取当前物体的刚体属性
        rb = GetComponent<Rigidbody>();
    }
    // 刷新的每一帧执行的函数
    void Update()
    {
        // 监听鼠标事件
        Vector3 moveDir = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")).normalized;
        // 移动距离 = 移动方向 * 移动速度 * 每一帧时间
        moveAmount = moveDir * moveSpeed * Time.deltaTime;
        
    }
    private void FixedUpdate()
    {
        // 物体移动
        rb.MovePosition(rb.position + moveAmount);
    }
}

Horizontal 和 Vertical 的设置地点:Edit下的ProjectSetting

2.3.3 脚本文件的挂载

点击cube,再点击Add Component,搜素脚本名称Move即可。

 

 2.4 物体的旋转与跳跃

脚本文件如下:

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

public class Move : MonoBehaviour
{
    public float moveSpeed = 5f;
    // 控制旋转速度
    public float rotateSpeed = 5f;
    // 控制跳跃高度
    public float jumpSpeed = 8f;
    Vector3 moveAmount;
    Rigidbody rb;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        Vector3 moveDir = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")).normalized;
        moveAmount = moveDir * moveSpeed * Time.deltaTime;
        // 获取旋转方向
        Vector3 targetDir = Vector3.Slerp(transform.forward, moveDir, rotateSpeed * Time.deltaTime);
        // 实现旋转
        transform.rotation = Quaternion.LookRotation(targetDir);
        // 实现按键跳跃
        if (Input.GetButton("Jump"))
        {
            transform.Translate(Vector3.up * Time.deltaTime * jumpSpeed);
        }
        
    }
    private void FixedUpdate()
    {
        rb.MovePosition(rb.position + moveAmount);
    }
}

猜你喜欢

转载自blog.csdn.net/zujiasheng/article/details/122718418