- Home /
Checking position doesn't work?
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;
}
Answer by bobisgod234 · May 26, 2017 at 04:00 AM
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);
}
would i be able to ask you another question here? [ related to this question ]
Sure, as long as it is related to this question.
At the moment it just moves in one speed, is it possible for it to smooth in then smooth out ? I have this so far :
if( curr_count == 0 ){
if( textobj.transform.position.x <= -12f){
speed = 0;
// clamp to -12
textobj.transform.position = new Vector3(-12f, textobj.transform.position.y, textobj.transform.position.z);
GetComponent(AudioSource).PlayOneShot(okSound);
moveText = false;
curr_count = 1;
openPlane();
}
}
Answer by methos5k · May 26, 2017 at 04:18 PM
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).