Unity, how to move a cube so that it always walks 1 in 1

Asked

Viewed 565 times

1

I’m creating a learning game in Unity (C#),made this code to move my player from one to one square

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

// Esta classe é responsável por movimentar e interagir o objeto Player
public class Player : MonoBehaviour {
    // Variáveis compostas
    private Vector3 speed; // speed é um vetor 3, ele representa cada direção que o Player anda (x e z)

    // Variáveis primitivas
    private float timer; // timer é um cronômetro, ele representa o tempo de deslocação do player

    // Métodos de MonoBehaviour
    public void start(){ // Quando o objeto é criado
        speed = new Vector3(0,0,0); // speed é iniciado com zero (Player parado)
        timer = 0; // timer inicia zerado (Player pode se mover)
    }

    public void update(){ // Enquanto o objeto existir
        if(timer > 0){ // se timer for maior que zero (cronômetro iniciado)
            timer -= Time.deltaTime; // timer dimui conforme delta time (1/fps)
            transform.Translate(speed * Time.deltaTime); // Player se move com base em speed veses delta time
        } else // senão
            move(); // Pode-se mover
    }

    // Métodos da classe
    public void move(){ // Move o player em x e z
        if(Input.GetKeyDown(KeyCode.A)){ // se existir entrada com tecla A
            speed.Set(-1,0,0); // modifica speed para -1 em x
            timer = 1; // inicia o timer
        } else if(Input.GetKeyDown(KeyCode.D)){ // se existir entrada com tecla D
            speed.Set(1,0,0); // modifica speed para 1 em x
            timer = 1; // inicia o timer
        }
    }
}

It doesn’t go sideways when I press the keys... What can it be???

  • To format your multi-line code, do not use ticks (inverted quote `); select lines of code and press ctrl+k. On your question, is your game RTA? Or is it based on turns? Will it get animation or will the character simply teleport? (Yes, I know the cube is a placeholder for the character, but modeling for proper use becomes easier by the actual object)

  • It’s just a learning game. I’m starting with Unity. It is a cube, which moves from 1 to 1, which has to drag objects x to places x. If all objects are in the given position... He goes through phase

1 answer

1

The problem

The functions Start and Update are in lower case. According to Unity documentation, Start and Update are in capital letters.

As nomenclature conventions of C# may be useful to you.

Suggestion

You can use GetAxisRaw in Unity instead of GetKeyDown in that situation. You put Input.GetAxis("Horizontal") as x and Input.GetAxis("Vertical") in the z vector speed within your Update(). The code will be more readable and compact.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.