Created
February 13, 2018 06:50
-
-
Save sdocy/c1af05209212e6bdbd3cc3844f48092b to your computer and use it in GitHub Desktop.
Move a Unity object from its current position to the position of another game object.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// stay within a certain range of target | |
void mvt_stayWithin() { | |
if (Vector3.Distance(transform.position, myStats.target.transform.position) <= myStats.targetRange) | |
// we are as close to the target as we want to be | |
return; | |
// get X and Y distance to target | |
float diffX = transform.position.x - myStats.target.transform.position.x; | |
float diffY = transform.position.y - myStats.target.transform.position.y; | |
// get the x and y direction to move in | |
if (diffX < 0) { | |
dir_x = 1.0f; | |
} else if (diffX > 0) { | |
dir_x = -1.0f; | |
} else { | |
dir_x = 0; | |
} | |
if (diffY < 0) { | |
dir_y = 1.0f; | |
} else if (diffY > 0) { | |
dir_y = -1.0f; | |
} else { | |
dir_y = 0; | |
} | |
// normalize movement to 1 for whichever is the larger gap, x or y | |
// this makes you move straight to your target | |
diffX = Mathf.Abs(diffX); | |
diffY = Mathf.Abs(diffY); | |
if (diffX > diffY) { | |
dir_y = dir_y * (diffY / diffX); | |
} else { | |
dir_x = dir_x * (diffX / diffY); | |
} | |
// move this object | |
transform.Translate(Time.deltaTime * dir_x * myStats.speed, Time.deltaTime * dir_y * myStats.speed, 0); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment