- Home /
Other
Make a moving object continue it's movement from the same direction , even it reaches target
Hello everyone, I'm stuck at a point in my game. I have a top-down camera, and a cube as a player. Cube fires projectiles by mouse click, we fire projectile to the position of mouse input, i achieved this with click to move code in unity wiki, basically we have our position defined as targetPosition in Attack.js .
Now in my projectile script, I did this :
private var positionToGo : Vector3;
function Start () {
positionToGo = Attack.targetPosition; // our var positionToGo equals to mouse input pos now
}
Now when I fire my projectile, it goes to the mouse input, that's cool. But it stays there, i want to make it continue it's way in the same direction but whatever i tried it always changes direction, I couldn't find any solution since I use this to move projectile to mouse position:
transform.position = Vector3.MoveTowards(transform.position, positionToGo, Time.deltaTime * projectileSpeed);
So I tried doing something like this :
if(Vector3.Distance(transform.position,positionToGo)>10 && canMoveToMouseClick)
{
transform.position = Vector3.MoveTowards(transform.position, positionToGo, Time.deltaTime * projectileSpeed);
// if projectile is still far away from mouse position, make it go to the mouse position
}
if(Vector3.Distance(transform.position,positionToGo)<10)
{
canMoveToMouseClick = false; // if it's close enough to mouse position, make a variable false
}
if(!canMoveToMouseClick)
{
// and if that variable is false, make the game object move without changing it's direction, but how ?
// you know something like
// transform.Translate(transform.forward * Time.deltaTime * projectileSpeed, Space.Self);
// but it doesnt work, it just changes direction both i tried self and world.
}
So can anyone help guys ? Thanks.
Answer by Inan-Evin · Dec 22, 2013 at 11:57 AM
Okay I solved it,
transform.Translate(directionObject.transform.forward * Time.deltaTime * projectileSpeed, Space.Self); // directionObject whose transform looks at mouse input position. I'm not deleting post maybe someone will have similar problem.