精灵没有在统一 2D C# 中移动

问题描述

我正在学习制作游戏的教程,但当我写下他们写的内容时,它不会移动。

脚本附加到精灵,但当我点击 WASD 时,它不会不要动。

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

public class Movment : MonoBehavIoUr
{
    // Start is called before the first frame update

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

    // Update is called once per frame
    void Update()
    {
           float h = Input.GetAxis("Horizontal");
           float v = Input.GetAxis("Vertical");

           Vector2 pos = transform.position;

           pos.x += h * speed * Time.deltaTime;
           pos.y += v * speed * Time.deltaTime;
    }
}

解决方法

由于 Vector2 是值类型(结构体),Vector2 pos = transform.position 将复制转换位置,并且原始位置不会受到您对 pos 所做的任何更改的影响。要更新位置,请在将 transform.position = pos 设置为新位置后使用 pos

void Update()
{
    float h = Input.GetAxis("Horizontal");
    float v = Input.GetAxis("Vertical");

    Vector2 pos = transform.position;

    pos.x += h * speed * Time.deltaTime;
    pos.y += v * speed * Time.deltaTime;
    transform.position = pos;
}

见:What's the difference between struct and class in .NET?