When i press D on my keyboard, I would like it to move to the right smoothly and stop when the position of textobj reaches -12. Unfortunately this doesn’t want to co-operate with me, Here is the script. There is no errors , The text does not stop scrolling when textobj reaches -12.
var Speed : float = 5;
var textobj : GameObject;
var canMove : boolean = true;
var OriginalSpeed : float = 5;
var moveText : boolean = false;
function Update (){
if( Input.GetKeyDown(KeyCode.D)){
if( canMove == true ){
moveText = true;
}
}
if( moveText == true ){
textobj.transform.position += Vector3.left * Time.deltaTime * Speed;
}
if( textobj.transform.position == Vector3(-12,0,0)){
Debug.LogWarning("test");
speed = 0;
}
}
function stopMovement (){
canMove = false;
Speed = 0;
yield WaitForSeconds(0.1);
Speed = OriginalSpeed;
canMove = true;
}
This is because of floating point (im)precision. A simple solution would be ‘<=’ the x portion of the position (as that seems to be the only part you’re testing. If it was more than that, you could use ‘Distance’ to measure and compare it to a small value (but not a precise one).
Add Debug.Log (textobj.transform.position). You will see that the number wont become precisely -12, but instead has some decimal on the end.
Since Time.deltaTime is usually some fraction (e.g. 0.0132323), your transform.position will never end up being precisely -12. Instead as its updates, it probably goes something like -11.58, -11.79, -11.97, -12.23 etc.
If you want the object to stop when it hits -12, you need to check if its exceeded -12, and clamp it to -12.
//check if past -12
if( textobj.transform.position.x <= -12f){
Debug.LogWarning("test");
speed = 0;
// clamp to -12
textobj.transform.position = new Vector3(-12f, textobj.transform.position.y, textobj.transform.position.z);
}