- Home /
What is the simplest way to move an object from Point A to Point B? (2D) (JS)
This is an absurdly simple question so I apologize, but all of my searches yield more complicated answers for more difficult problems that I can't understand without understanding this.
I have a game object, as soon as the object is instantiated I want it to move from point A to point B, just once, and sit there at point B:
Point A is the point at which the object is instantiated, it's a Vector3 (or at least I think it should be; Vector2 has been giving me fits so I've just been using Vector3 and placing 0 on the z axis). But let's just say it's (1,1,0), because for the purpose of my question it doesn't matter what the actual value is.
Point B is a randomly chosen point, but let's just say it's the origin (0,0,0).
All I want to do for the time being is have the object move from point A to point B either over some period of time or at some speed. I already know that I will need to define a public variable "speed" and multiply something by that, or fill out a period of time that it should take to move from point to point. That's all I can figure out though. I'm not even quite sure if I should store this all in function Start, function Update (hopefully not), or if I'll need to use a loop to get it working. The action will be taking place completely independently of user input so I don't think it'll go in function update or require a loop, but I'm quite new so I may be mistaken.
Many thanks!
Answer by Grimrender · Mar 13, 2014 at 06:01 AM
I managed to kind-of get my script working, in case anyone comes across this question in the future. It looks something like this:
#pragma strict
var pointB : Vector3;
var maxSpeed: float = 1.0;
function Update () {
var change = maxSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, pointB, change);
}
Every frame the object moves from it's transform.position (point A) towards pointB at a rate controlled by maxSpeed and Time.deltaTime (as near as I can tell, anyway, that's what's happening). However this hasn't proven useful to me so-far as it can't output any sort of speed for use with an animation (again, as far as I can tell). I'm looking into doing this other ways, maybe using a ridigbody2D? I'll post back if I manage to figure out a more appropriate and useful answer.
Perfectly good answer. You might also take a look at the $$anonymous$$oveObject script in the Unity Wiki. In addition, if all you are interested in is the moving and not the code, take a look at iTween. It is free in the Asset store.
Your answer
Follow this Question
Related Questions
Smooth Movement Transition 2 Answers
Automatic Movement Script 1 Answer
Increase speed in coroutine gives side-effect in movement 0 Answers