初识Unity

这是我们Unity的主界面

分为五个板块

Scene:场景视图

Game:游戏试图

Hierarchy:层级试图

Project:项目管理试图

Inspector:检查试图

第一节课:实现物体移动脚本

在Hierarchy右键创建一个3D 圆柱物体:Cylinder

在Project的Assets下右键创建一个脚本文件夹:Scripts

在Scripts下创建一个Move文件夹

 在Move文件夹下创建一个Move C#脚本

 让我们双击进入来编写 移动脚本

第一种:我们可以通过按键来控制移动

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

public class Move : MonoBehaviour
{   
    //创建对象
    public GameObject obj;
    //赋予速度
    public float speed = 10;
    void Start()
    {
        
    }
    // Update is called once per frame
    void Update()
    {
       
        if (Input.GetKey("w"))
            transform.Translate(0, 0, 1f);
        if (Input.GetKey("s"))
            transform.Translate(0, 0, -1f);
        if (Input.GetKey("a"))
           transform.Translate(1f, 0, 0);
        if (Input.GetKey("d"))
            transform.Translate(-1f, 0, 0);

    }
}

第二种:我们可以通过虚拟轴来控制移动

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

public class Move : MonoBehaviour
{   
    //创建对象
    public GameObject obj;
    //赋予速度
    public float speed = 10;
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        float horizontal = Input.GetAxis("Horizontal");//水平虚拟轴
        float vertical = Input.GetAxis("Vertical");//垂直虚拟轴

        obj.transform.Translate(0, 0, vertical * speed * Time.deltaTime);//time.deltaTime 时间增量
        obj.transform.Translate(horizontal, 0, 0 * speed * Time.deltaTime);
        //if (Input.GetKey("w"))
        //    transform.Translate(0, 0, 1f);
        //if (Input.GetKey("s"))
        //    transform.Translate(0, 0, -1f);
        //if (Input.GetKey("a"))
        //    transform.Translate(1f, 0, 0);
        //if (Input.GetKey("d"))
        //    transform.Translate(-1f, 0, 0);

    }

这两种都可以实现物体的移动。

然后我们将脚本拖到物体上

我们就实现物体的移动啦!

猜你喜欢

转载自blog.csdn.net/Cddmic/article/details/126265513
今日推荐