Having projectile face mouse position
I'm trying to create a projectile that will face and move towards the direction of where the mouse was when the player clicked to fire.
I've tried a couple of ways to do this but they don't work very well. This is currently the script I'm using to create and change the rotation of the fireball:
void FireBall()
{
Vector2 dir = Input.mousePosition - transform.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
GameObject fireballObject = Instantiate(fireBall, firePoint.transform.position, Quaternion.identity) as GameObject;
if(transform.localScale == new Vectohttp://answers.unity3d.com/questions/ask.html?space=8#r3(1, 1, 1))
{
fireballObject.transform.localScale = new Vector3(1, 1, 1);
fireballObject.GetComponent<FireBall>().ApplyForce(transform.right);
fireballObject.transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
else if(transform.localScale == new Vector3(-1, 1, 1))
{
fireballObject.transform.localScale = new Vector3(-1, 1, 1);
fireballObject.GetComponent<FireBall>().ApplyForce(-transform.right);
fireballObject.transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
This is what happens when I test it:
The red circle is where my mouse was when I clicked but as you see, the fireball isn't facing that direction and I'm not sure why.
Anyone small thing that I also can't get working is making the projectile move the direction it's facing.
Could anyone help me?
Answer by Eno-Khaon · May 09, 2016 at 12:17 AM
The problem lies at the very beginning:
Vector2 dir = Input.mousePosition - transform.position;
Input.mousePosition gives you the position of your cursor... on the screen. You need to convert that to world space, first.
At a glance, your environment appears to be 2D, so I'll base my example around that assumption.
A simple conversion of screen coordinates into world position can be done using something like:
Vector3 worldMousePosition3D = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 mousePosition = new Vector2(worldMousePosition3D.x, worldMousePosition3D.y);
Then, you can use the result instead, for:
Vector2 dir = mousePosition - transform.position;
Your answer
Follow this Question
Related Questions
How could I make the children of an object face the direction it is moving on the y-axis? 0 Answers
Rotate non-forward vector to face direction? 0 Answers
Object rotates normaly while moving, then does zig zags? 0 Answers
Struggling to get the rotation the player is moving in. 1 Answer
How to make an object rotate in the direction using horzontal and vertical input axis? 0 Answers