【问题标题】:Sprite not moving in unity 2D C#精灵在统一 2D C# 中不移动
【发布时间】:2021-09-29 23:32:29
【问题描述】:

我正在学习制作游戏的教程,但是当我写他们写的东西时,它不会动。

脚本附加到精灵,但是当我点击 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;
    }
}

【问题讨论】:

    标签: c# unity3d game-development


    【解决方案1】:

    由于Vector2 是一个值类型(结构),Vector2 pos = transform.position 将复制转换位置,原始位置不受您对pos 所做的任何更改的影响。要更新位置,请在将 pos 设置为新位置后使用 transform.position = 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?

    【讨论】:

    • 那我该怎么办?
    • @BraydenTodorov 您需要将 pos 应用回精灵位置。
    • @BraydenTodorov 如果此解决方案对您有用,请不要忘记接受答案!
    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    相关资源
    最近更新 更多