- Home /
moving objects with transform position
I have this strange problem. direction is a Vector 2 and i'm trying to move objects by transform.position so here's the code
gameObject.transform.position = new Vector2(direction.x Time.deltaTime Speed, direction.y Time.deltaTime Speed);
but they move really fast and i dont know the reason. Speed is a float variable which equals to 4f but even if i change it to something like 0.00000000000000000000004f nothing changes. I dont understand the reason of this
Use transform.Translate bro! it will work perfectly!
//
transform.Translate(new Vector2(direction.x * Time.deltaTime * speed, direction.y * Time.deltaTime * speed));
//
dont you think you should do like
`gobj.transform.position = new Vector3(gobj.transform.position.x+direction.x * Time.deltaTime * speed,
gobj.transform.position.y+direction.y* Time.deltaTime * speed,
gobj.transform.position.z);`
??
Answer by morbidcamel · Sep 09, 2014 at 06:55 AM
It seems that you need to do a -> pos +=
Make sure your direction is normalized e.g. direction = direction.normalized
speed of 4 means 4 meters a second in the given example which is quite fast
Make sure your direction is actually not == Vector3.zero
Make sure you call this in "void Update()" if you're calling it from void FixedUpdate() you need to use Time.fixedDeltaTime
Answer by Lasconik · Sep 09, 2014 at 12:05 PM
Be careful: when setting directly the position, the physic engine could miss collisions. I suggest using Rigidbody.Translate (or at least Transform.Translate, to keep clean things).
Answer by Jeredriq · Sep 09, 2014 at 01:06 PM
I used casting
gameObject.transform.position +=(Vector3)new Vector2(direction.x, direction.y ) * -Speed;
to solve the problem
Although it's a 2D project, gameObject.transform.position was Vector3. I dont know why
That's not what solved your problem the fact that you accumulating += ins$$anonymous$$d of assigning = is what solved the problem. Vector2d and Vector3d implicitly cast to each other.