Hello all. I am currently creating a simple script that moves an object’s transform, in this instance named rbSection0, towards the transform of my player, called currentPlayerPosition.
The code above does just this fine. However, it’s a little limited because I want the object to accelerate as the player moves away from it. I thought that maybe scaling it using Unity’s Vector3.Distance would work, but the outcome is terrible. The object jitters around and doesn’t really move. So, I created my own distance variable called trueDistance, to scale the movement as distance increases. This results in the exact same result. (which admittedly I expected, I doubt I’m doing it too much differently than Unity does) The following implementation is below:
MoveTowards works pretty well and you’re using it correctly – current location, target location, distance to move this frame. I’ve used it to get smooth yet variable movement by playing with the moveAmount in much the same manner you are (basically, I never use smoothDamp since it’s easier to make it with MoveTowards). Your idea is fine. MoveTowards has a sometimes surprising feature that doesn’t matter in your case (since I assume the enemies or the player dies first): it stops at the target, not moving past.
I’d guess you’re doing something else funny, like resetting the position somewhere else, or putting that code somewhere funny, or not updating playerPosition … . I’m also wondering if scaling the speed based on linear distance is giving too much of a boost. Using the square root (or cube root) or even the log of the distance might give a nicer-looking further-is-faster look. Or maybe it just looks bad tracking a moving player and the target should be the player plus a few seconds of estimated movement.
And unrelated, if you want to write your own distance, it’s fine to precompute things you’re going to use twice: float xd=(myX-theirX), yd=(myY-theirY) … ; float dist=Sqrt(xdxd+ydyd … ); .
Some solid advice. I probably should create a corresponding Xd, Xy, Zd and distance just for the sake of readability alone. I should also try to work with having a curve to the enemy speed rather than have it be directly correlated with the player speed, but I’d have to toy with it since the player can knock the enemy back with their shots and can jump to different areas of the arena. I have have adjust the speed based on their AI state. I should check my scripts line by line to see if anything is messing with the player position variable, but it is being updated regularly and printing the value to the console doesn’t seem to have anything wrong with it, but I’d have to check that value at multiple points.