Search Unity

box won't move...

Discussion in 'Scripting' started by ImGundulf, May 24, 2020.

  1. ImGundulf

    ImGundulf

    Joined:
    May 17, 2020
    Posts:
    49
    box won't move to the left to right it should, but for me it only stand still.
    Here's my code if you see an error on it. thanks!
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class BoxScript : MonoBehaviour {
    6.  
    7.     private float min_X = -2.2f, max_X = 2.2f;
    8.  
    9.     private bool canMove;
    10.     private float move_Speed = 2f;
    11.  
    12.     private Rigidbody2D myBody;
    13.  
    14.     private bool gameOver;
    15.     private bool ignoreCollision;
    16.     private bool ignoreTrigger;
    17.  
    18.     void Awake() {
    19.         myBody = GetComponent<Rigidbody2D>();
    20.         myBody.gravityScale = 0f;
    21.     }
    22.    
    23.     // Start is called before the first frame update
    24.     void Start() {
    25.         canMove = true;
    26.  
    27.         if(Random.Range(0, 2) > 0) {
    28.             move_Speed *= -1f;
    29.     }
    30.  
    31.     // Update is called once per frame
    32.     void Update() {
    33.         MoveBox();
    34.     }
    35.  
    36.     void MoveBox() {
    37.         if(canMove) {
    38.  
    39.             Vector3 temp = transform.position;
    40.  
    41.             temp.x += move_Speed * Time.deltaTime;
    42.  
    43.             if(temp.x > max_X) {
    44.                 move_Speed *= -1f;
    45.                
    46.             } else if (temp.x < min_X) {
    47.                 move_Speed *= -1f;
    48.             }
    49.  
    50.             transform.position = temp;
    51.             }
    52.        }
    53.     }
    54.  
    55. }
    56.  
     
  2. exiguous

    exiguous

    Joined:
    Nov 21, 2010
    Posts:
    1,749
    What do you think how other people solve such problems? It's called "debugging". This means that you try to find the source of the error. The easiest thing is to place Debug.Log messages at strategical positions in your code and verify the validity of your assumptions. What values does the variables have? Which path does the program flow take? What are the results of the calculations? You simply can't ask the forums for every tiny error/bug/problem you have. If you want to be a programmer you HAVE TO learn how to debug. Start right away and just do it. This way you will learn much more about programming and how computers work than by copying some corrected code someone posted.
     
    DaDonik likes this.
  3. ImGundulf

    ImGundulf

    Joined:
    May 17, 2020
    Posts:
    49
    ok, thanks! :) I will start to do that then! :D