- Home /
GameObject wont stop rotating ?
Hey, I created a code to make my GameObjects move to where i click with my mouse.
this.pos is the final position.
CC is the CharacterControl.
I used the around method so the GameObject will stop around the final position because there is no chance that he will get to the exact position.
public bool around(Vector3 num, Vector3 around, float prec)
{
bool flag = true;
if(num.x > around.x + prec || num.x < around.x - prec)
flag = false;
if(num.y > around.y + prec || num.y < around.y - prec)
flag = false;
if(num.z > around.z + prec || num.z < around.z - prec)
flag = false;
return flag;
}
void Update () {
if(!around(myTransform.position, this.pos, 0.5f))
{
int _turn = 0; // left = -1; none = 0; right = 1;
Vector3 dir = (pos - myTransform.position).normalized;
float direction = Vector3.Dot(dir, transform.forward);
if(direction > 0.9f)
CC.SimpleMove(myTransform.forward * moveSpeed);
dir = (pos - myTransform.position).normalized;
direction = Vector3.Dot(dir, transform.right);
if(direction > 0.3f) {
_turn = 1;
}
else if(direction < 0.3f) {
_turn = -1;
}
else {
_turn = 0;
}
myTransform.Rotate(0, _turn * Time.deltaTime * rotationSpeed, 0);
}
}
The problem is that when the unit reaches around the final pos, he keeps rotating a little left a little right but without moving so it will never reach the desired pos and will never stop rotating..
yup that interesting... so you think it will never stop rotating because it will never literally get to exact position ?
Yes, i mean it always gets inside the if(!around... because it never gets around that point..
In an else ($$anonymous$$eaning it is around the object, yeah?) you could remove this script.... Destroy(this);. Or no? Lol.
Answer by ks13 · Dec 08, 2011 at 02:52 PM
Actually, why not use Vector3.MoveTowards(currentPosition, targetPosition, distance); If you make the distance a percentage of the total distance you won't have to worry about never attaining the targeted position.
You should get something like :
void Update () {
if(myTransform.position != this.pos)
{
percentageDone += step;
myTransform.position = Vector3.MoveTowars(beginingPosition, this.pos, Vector3.Distance(beginingPosition, this.pos) * percentageDone);
myTransform.Rotate(0, Time.deltaTime * rotationSpeed, 0);
}
}
Where percentageDone is the % of distance already traveled by the object, and step the % you want your object to move every frame.
Your answer
Follow this Question
Related Questions
Movement relative to Camera and XZ Plane 1 Answer
Character MoveLook rotation locked? 1 Answer
Setting Up Vector and Still Rotating the Character 1 Answer
Character Controller Movement - Different speeds on different axis 1 Answer
Rotate the camera around a gameObject with a dynamic up value. 0 Answers