Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

My square won't move when I press A or D?

Discussion in 'Scripting' started by Vega2022, Jan 17, 2022.

  1. Vega2022

    Vega2022

    Joined:
    Jan 17, 2022
    Posts:
    2
    I gave both the square and the surface that the square is supposed to move on 2d box colliders, and gave the cube a rigid body.

    Here's the code I'm using:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    public class Moving_Cube : MonoBehaviour
    {
    public float cubeSpeed;
    // Start is called before the first frame update
    void Start()
    {

    }
    // Update is called once per frame
    void Update()
    {
    if (Input.GetKey(KeyCode.D))
    {
    gameObject.transform.Translate(Vector2.right * Time.deltaTime * cubeSpeed);
    }
    else if (Input.GetKey(KeyCode.A))
    {
    gameObject.transform.Translate(Vector2.left * Time.deltaTime * cubeSpeed);
    }
    }
    }
     
  2. Vega2022

    Vega2022

    Joined:
    Jan 17, 2022
    Posts:
    2
    Nvm. Ignore this. I figured it out
     
  3. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,316
    For the future though, please use code-tags when posting code and not plain text.

    Thanks.