Unity2D教程:人物移动

关注专栏,持续更新哦

教程总目录

按键

自带的Input有GetAxisRaw来获取按下按键后所对应的值,Input.GetAxisRaw(“Horizontal”)在按下D或右箭头返回1,A或左箭头返回-1;Input.GetAxisRaw(“Vertical”)同理。

Input.GetAxis会根据按下时间返回小数,类似于有了加速度

        float moveX = Input.GetAxisRaw("Horizontal");
        float moveY = Input.GetAxisRaw("Vertical");

位置

创建一个3D物体,例如Sphere。
可以看到其中有一个Transform的组件控制其位置旋转度和大小。
在这里插入图片描述

通过transform.position获得包含XYZ信息的Vector3对象,可以隐式转化为包含XY信息的Vector2对象。

移动

通过设置其position即可改变位置,Time.deltaTime为一帧的时间,speed为自己设置的速度。

    public float speed = 5;
        Vector2 p = transform.position;
        p.x += moveX * speed * Time.deltaTime;
        p.y += moveY * speed * Time.deltaTime;
        transform.position = p;

代码

using System.Collections;
using System.Collections.Generic;
using UnityEditor.UIElements;
using UnityEngine;

public class PlayerMoving : MonoBehaviour
{
    // Start is called before the first frame update

    public float speed = 5;
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        float moveX = Input.GetAxisRaw("Horizontal");
        float moveY = Input.GetAxisRaw("Vertical");
        Vector2 p = transform.position;
        p.x += moveX * speed * Time.deltaTime;
        p.y += moveY * speed * Time.deltaTime;
        transform.position = p;
    }
}

使用

将脚本拖入对象即可自动生成组件。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/jk_chen_acmer/article/details/106942566
今日推荐