【问题标题】:Sprite Movement Troubleshooting help in Unity?Unity 中的 Sprite 运动故障排除帮助?
【发布时间】:2020-03-30 19:32:20
【问题描述】:

我试图让一个对象在 Unity 中每秒移动一次,但它似乎不起作用。我正在尝试制作游戏蛇,我首先将头部的 Sprite 居中,然后每秒将其向右移动,然后添加玩家控件。 有什么帮助让它工作吗?

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

public class Snake_Move : MonoBehaviour
{
    private Vector2 pos;
    private Vector2 moveDirection;
    private float moveTimer;
    private float timerSeconds;

    private void Startup()
    {
        pos = new Vector2(5, 5);
        timerSeconds = 1f;
        moveTimer = timerSeconds;
        moveDirection = new Vector2(1, 0);
    }

    private void Update()
    {
        moveTimer += Time.deltaTime;

        if (moveTimer > timerSeconds)
        {
            pos += moveDirection;
            moveTimer -= timerSeconds;
        }

        transform.position = new Vector2(pos.x, pos.y);
    }
}

【问题讨论】:

    标签: c# windows unity3d


    【解决方案1】:

    Startup 永远不会被调用,因此您的所有值都将保持其默认值 - 特别是 pos = Vector2.zeromoveDirection = Vector2.zero,因此您的对象将永远不会移动。


    您可能更愿意将其称为 Start 以实现自动调用的 Unity 消息 MonoBehaviour.Start

    在第一次调用任何 Update 方法之前启用脚本时的帧上。

    public class Snake_Move : MonoBehaviour
    {
        // These you adjust in the Inspector in Unity
        // Later changes to the values here will have no effect!
        [Tooltip("Time interval between steps in seconds")]
        [SerializeField] private float stepInterval = 1f;
    
        [Tooltip("Initial position")]
        private Vector2 startPos = new Vector2(5, 5);
    
        private Vector2 moveDirection;
        private float moveTimer;
    
        // What you wanted is probably the Unity message method Start
        // which is called when you app starts
        private void Start()
        {
            moveTimer = stepInterval;
            moveDirection = Vector2.right;
    
            transform.position = startPos;
        }
    
        private void Update()
        {
            moveTimer += Time.deltaTime;
    
            if (moveTimer > stepInterval)
            {
                moveTimer -= stepInterval;
    
                // No need to store the pos, simply only assign a new value
                // to the position when needed
                transform.position += moveDirection;
            }
        }
    }
    

    【讨论】: