dezox
dezox

Reputation: 179

How do I move a sphere towards, starting from players position?

Im making a game in Unity. My task is to when player presses the "1' key, it shoots out a sphere to the player.transform.forward position, until it collides with an enemy.

The problem is, when the sphere has been shot, while its flying, I can controll its moving X value by turning the player right or left. So the sphere moves with me, but it should not. This is of course because in Update(), I move it in the player's facing direction. How can I make the sphere start facing at the players direction, but after move independently?

This is the code that moves the sphere

private float speed = 4.0f;

void Update()
    {
        transform.Translate(player.transform.forward * Time.deltaTime * speed);
    }

Upvotes: 1

Views: 104

Answers (2)

derHugo
derHugo

Reputation: 90659

Instantiate it with the correct orientation

Instantiate(rangedAttack, spawnPosition, player.transform.rotation);

Now its own forward vector points the same direction as the one of the player.

And then simply do

private float speed = 4.0f;

void Update()
{
    transform.Translate(Vector3.forward * Time.deltaTime * speed);
}

Note Translate by default works in the Space.Self so the local space of this transform. You do not want to pass in a worldspace Vector here but rather move only in the local Z axis!

If you pass in a worldspace vector you will nee to pass Space.World

transform.Translate(vector, Space.World);

Upvotes: 1

Innat3
Innat3

Reputation: 3576

You could save it's inital "forward" direction and reference it afterwards

public GameObject player;

private float speed = 4.0f;
private Vector3 direction;

private void Awake() //I used Awake() as example asuming you are instantiating the sphere, 
{                    //but you could set the value of the direction when you press "1" too

    direction = player.transform.forward;
}

void Update()
{
    transform.Translate(direction * Time.deltaTime * speed);
}

Upvotes: 1

Related Questions