3
votes

I'm trying to design a spitball/poison type projectile that will travel until it reaches the point clicked on screen and then destroys itself. The problem is that contrary to what almost everyone says, Vector3.Movetowards is not moving the ball at a constant speed. If the target location is close to the launcher it moves slowly, if it is further away it moves much faster.

public float speed = 5f;
public Vector3 target = new Vector3();
void Update()
{

    transform.position = Vector3.MoveTowards(transform.position, target,speed * Time.deltaTime);
}

Adding the launcher script

 private void Shooting()
{
    if (Input.GetMouseButton(0))
    {
        if (Time.time >= shotTime)
        {
           
            GameObject poison = Instantiate(Projectile, shotPoint.position, transform.rotation);
            Vector3 target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            target.z = 10f;
            poison.GetComponent<PoisonBall>().target = target;
            shotTime = Time.time + timeBetweenShots;
        }
    }
}
1
If you're creating a "launcher" you may want to look at using a rigidbody and applying force so that you can get an arc from the physics. However, your MoveTorwards code looks right. Is target currently being set in the editor, or code not shown?dgates82
Target is set by the launcher (it already faces the direction the mouse is pointing) after instantiating the object, the target is set to the current mouse position using screentoworldpoint.agentsmith200
Vector3.MoveTowards moves the current position towards the target with whatever speed (or better maximum step size per call) you pass in, if it is constant linear and the target position doesn't change meanwhile then the movement will be so. The behavior you describe is not reproducible or missing additional information specific to your casederHugo
I added the code from the launcher (more a gun than a launcher) that instantiates the poison ball.agentsmith200

1 Answers

1
votes

Is the balls start position also at z=10f? Otherwise the difference in the speed most probably is a perspective issue in a 2D game and results in your bullet traveling in the Z direction but from your camera perspective you don't see that.

=> The closer you will be to the target the more movement will only happening on the Z axis, the further away the more movement is happening on X and Y.

Make sure to also do

var spawn = shotPoint.position;
spawn.z = 10f;
GameObject poison = Instantiate(Projectile, spawn, transform.rotation);

Or alternatively keep target.z = 0 (just remove the line target.z = 10f as per default the ScreenToWorld uses the Z component of given vector as depth and you are passing in a 2D vector with 0 depth anyway) and instead use Vector2.MoveTowards which will ignore ant depth on Z.