Hi,
I have an orthographic camera which is sat directly behind my character, raised somewhat and looking down on him. I am aiming to fire a prefab in the direction of the mouse. I’ve looked all over and I feel like I’m close but I can’t quite get the right results.
//float dist = Camera.main.transform.position.y-transform.position.y;
//Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.mainCamera.transform.position.y);
Vector3 targetPos = Camera.main.ScreenToWorldPoint(mousePos);
targetPos.y = (float)(transform.position.y + 1.3);
Vector3 spawnPos = new Vector3((float)(transform.position.x), (float)(transform.position.y + 1.3), transform.position.z);
GameObject abil = (GameObject)Instantiate(Resources.Load("fireball"), spawnPos, Quaternion.LookRotation(targetPos));
abil.GetComponent<Fireball>().Ignore = "player";
abil.transform.LookAt(targetPos);
abil.rigidbody.AddForce(abil.transform.forward * ability.Speed);
This code only fires ‘north’, towards the top of the screen, but sort of loosely goes to the mouse position, but only within a restrictied cone from the player.
If I uncomment the first two lines in place of the third, I get different behaviour. The fireballs go southwards, loosely towards the mouse position, unless I go to the very top of the screen where it will begin to aim northwards.
Clearly I’ve got something wrong here. I did try something to do with creating a plane and raycasting, but that had similar effects the code shown.
Hope this is clear. Appreciate any replies.
Quick update to this: If I comment out this line: targetPos.y = (float)(transform.position.y + 1.3); And change this line: Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 5); Then the prefab moves towards the cursor, but it flies upwards. I was setting the Y so it fires directly forward from the spawn point. It seems like my code isn't taking into account camera rotation or something. With the code in the original post, the X and Y seem right, but the Z is wrong.
– GeneralMidi