繁体   English   中英

Unity 中的精灵运动故障排除帮助?

[英]Sprite Movement Troubleshooting help in Unity?

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

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);
    }
}

那么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;
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM