-1

I recently started developing my very first top down 2d game. My problem is not knowing exactly how to get the bullet to go where the mouse is facing at the time of the activation of the bullet. I have a face mouse function as seen here

void faceMouse()
{

    Vector3 mousePosition = Input.mousePosition;
    mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);

    Vector2 direction = new Vector2(
        mousePosition.x - transform.position.x,
        mousePosition.y - transform.position.y);

    transform.up = direction;
}

However, I am not sure how to incorporate that if at all to be able to shoot at the location of my mouse. Thanks in advance!

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
c0d3d
  • 13
  • 2
  • You are not sure how to incorporate the faceMouse function or the shoot bullet function. – Savaria Mar 12 '19 at 03:09
  • I am not sure what you mean? – c0d3d Mar 12 '19 at 03:53
  • That was meant to be a question, sorry it's getting late. You need help for the faceMouse function or for shooting bullets? – Savaria Mar 12 '19 at 04:09
  • So what is it you have trouble with? Getting the bullet to move? Are you using RigidBody? – derHugo Mar 12 '19 at 04:09
  • I am having trouble with not being able to shoot the bullets in the right direction. Sorry for the late response. – c0d3d Mar 12 '19 at 04:18
  • I am going to sleep now so I will not be able to respond further for a good many hours. I hope there is enough information to the point where my problem is clear. – c0d3d Mar 12 '19 at 04:53

1 Answers1

0

You could try Quaternion.LookRotation() which creates a rotation based on a forward and upward vector (Documentation). Then you need to assing that rotation to your object. I use it something like this:

cursorPos = mainCamera.ScreenToWorldPoint(Input.mousePosition);
var forwardDirection = transform.position - cursorPos;
//Vector3.forward because is the z axis which is up/down in 2D
Quaternion playerRotation = Quaternion.LookRotation(forwardDirection, Vector3.forward);
transform.rotation = playerRotation;
Nicolas
  • 440
  • 4
  • 13