Moodie
Moodie

Reputation: 35

Projectile not shooting direction of my weapon

So my game is sort of like a 3d top down shooter, so I want my gun to shoot wherever the mouse is and it wont go to the mouse unless im shooting down. If you've seen brackyes game called ball wars, im sort of trying to replicate one like that but the projectile is not shooting the right way.

I got my script from blackthornprods ranged combat tutorial (which is for 2d so maybe thats the issue but I dont know how to solve it) :

public float speed;
public float lifeTime;

private void Start()
{
    Invoke("DestoryProjectile", lifeTime);
}

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

void DestroyProjectile()
{
    Destroy(gameObject);
}

Appreciate anyone to try!

Here is my other script: Camera mainCam;

public GameObject projectile;

public Transform shotPoint;

private float timeBtwShots;
public float startTimeBtwShots;

void Awake()
{
    mainCam = Camera.main;
}

void Update()
{
    float objectDepthFromCamera = Vector3.Dot(
            transform.position - mainCam.transform.position,
            mainCam.transform.forward);

    Vector3 cursorWorldPosition = mainCam.ScreenToWorldPoint(Input.mousePosition
            + Vector3.forward * objectDepthFromCamera);

    Vector3 localUpNeeded = Vector3.Cross(Vector3.forward,
            cursorWorldPosition - transform.position);

    transform.rotation = Quaternion.LookRotation(Vector3.forward, localUpNeeded);

    if(timeBtwShots <= 0)
    {
        if (Input.GetMouseButtonDown(0))
        {
            Instantiate(projectile, shotPoint.position, transform.rotation);
            timeBtwShots = startTimeBtwShots;
        } 
    }
    else
    {
        timeBtwShots -= Time.deltaTime;
    }
}

Upvotes: 0

Views: 1100

Answers (1)

Maifee Ul Asad
Maifee Ul Asad

Reputation: 4577

Projectile not shooting direction of my weapon. Simple solution -

  • First instantiate or pool the instance of projectile.
  • Set rotation of projection from the rotation of weapon & set location to spawn point
  • Now fire, or whatever strategy you are using

Consider Global rotation, if you need help, tell me, I will edit and give a snippet of code.

This should work. If doesn't post all necessary code, I will give a better solution.

Here is sample github project I created, just for you. I opened Unity nearly after a year. Please check all the versions.

Must check :

firing in facing direction 💋 
just instantiate at spawn point
just added some rotation

I think this should give you concept.

Press X for a rantom rotation
Press Space to shoot a projectile :lol:
The white cube shows that it always shoots at a constant direction

Upvotes: 1

Related Questions