Ven Nilson
Ven Nilson

Reputation: 1019

Cube moving along x-axis issue

It's a 2d cube and moving along x-axis from right side to left side with the given speed. Also i added a component RigidBody2D in which it's velocity move this cube downward side. I disable the Rigidbody2D and want to move this cube straight along x-axis from right side to left side with the given speed i don't know how to do it. Code:

public class Move : MonoBehaviour 
{
   private float speed = -3f;
   //private Rigidbody2D body;

   /*
   void Awake()
   {
      body = GetComponent<Rigidbody2D> ();
   }
   */

   void Update () 
   {
      //body.velocity = new Vector2 (speed,0f);
   }
}

Upvotes: 2

Views: 101

Answers (2)

Nika Kasradze
Nika Kasradze

Reputation: 3019

Once again: transform.position is not a variable. It's a property.

Let me define it in this way - property is like a locked box of gears in a machine, you can not change whatever's inside while it is in the machine. You can only replace that box with a new box. So what you do is take that box out of the machine, THEN tweak it and put it back only after you are done. And this is what I do in this code:

public class Move : MonoBehaviour 
{
   private float speed = -3f;

   void Update () 
   {
      Vector3 pos = transform.position;
      pos.x += speed * Time.deltaTime;
      transform.position = pos;
   }
}

google properties vs variables for more info

Upvotes: 1

Marius Junak
Marius Junak

Reputation: 1213

you cant change the x coordinate, you have to make a new Vector3 with the updated x-coordinate

public class Move : MonoBehaviour 
{
   private float speed = -3f;

   void Update () 
   {
      transform.position = new Vector3(transform.position.x += speed * Time.deltaTime,transform.position.y,transform.position.z);
   }
}

Upvotes: 1

Related Questions