c# - How to stop Translate when I need? -


i have cupboard boxes. when on box , press mouse button, want open/close translate. want move box, till it's x coordinate 1.0 (and start point 1.345). moves longer point.

enter image description here

i tried use fixedupdate, doesn't helped..

public layermask mask;  private bool shouldclose; private bool changexcoordinate; private transform objecttomove;  void update () {     if (changexcoordinate)         openclosebox();     else if(doplayerlookatcupboardbox() && input.getmousebuttondown(0))         changexcoordinate = true; }  bool doplayerlookatcupboardbox() {     raycasthit _hit;     ray _ray = camera.main.screenpointtoray(new vector3(screen.width / 2, screen.height / 2, 0));     bool ishit = physics.raycast(_ray, out _hit, 1.5f, mask.value);      if (ishit && !changexcoordinate)     {         objecttomove = _hit.transform;         return true;     }     else         return false; }  void openclosebox() {     if (shouldclose)     {                  if(objecttomove.position.x != 1.345f) // must stop @ point, don't         {             changexcoordinate = false;             shouldclose = !shouldclose;         }         else             objecttomove.translate(vector3.right * time.deltatime);     }     else     {         if (objecttomove.position.x >= 0.1f) // same problem here..         {             changexcoordinate = false;             shouldclose = !shouldclose;         }         else             objecttomove.translate(vector3.left * time.deltatime);                 } } 

in kind of situation, should use animation, allows full control on aspect of movement.

if want use code, use vector3.movetowards creates linear translation position position b step amount per frame:

transform.position = vector3.movetowards(transform.position, targetposition, step * time.deltatime); 

as issue, checking if position float. comparing float not accurate in computer due inaccuracy of value.

1.345 1.345xxxxxx , not same 1.34500000. never equal.

edit: using equality results in fact checking if value greater or equal. consider this:

start : 10 movement : 3  if(current >= 0){ move(movement);}  frame1 : 10 frame2 : 7 frame3 : 4 frame4 : 1 frame5 : -2 stop here 

this why should use animation or movetowards when wishing move exact point. or add extra:

if(current >= 0){ move(movement);} else { position = 0; } 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -