- Home /
Cannot get mouse position in 2D using perspective
I am trying to make a side-on (would call it 2D but I guess it's not since I'm using perspective) game using the perspective camera to show depth. In orthographic mode my code works fine, the character will fire a ray between itself and the mouse cursor, but when I switch to perspective camera, this stops working.
I can only assume it's because using perspective it treats it as a vector3, rather than the vector2 I need... I'm stuck on how to achieve the same effect using a perspective camera.
This is my code that works using the orthographic camera:
void Shoot()
{
//translate mouse position into world coordinates
Vector2 mouseposition = new Vector2 (Camera.main.ScreenToWorldPoint (Input.mousePosition).x, Camera.main.ScreenToWorldPoint (Input.mousePosition).y);
Vector2 firePointPosition = new Vector2 (firePoint.position.x, firePoint.position.y);
RaycastHit2D hit = Physics2D.Raycast (firePointPosition, mouseposition-firePointPosition, bulletRange, whatToHit);
if (Time.time >= timeToSpawnEffect)
{
Effect();
timeToSpawnEffect = Time.time + 1/effectSpawnRate;
}
Effect();
Debug.DrawLine (firePointPosition, (mouseposition-firePointPosition)*bulletRange);
if (hit.collider != null)
{
//Debug.DrawLine (firePointPosition, hit.point, Color.red);
//Debug.Log ("Hit " + hit.collider.name + " for " + damage + " Damage.");
EnemyController enemy = hit.collider.GetComponent<EnemyController>();
if (enemy!= null)
{
enemy.DamageEnemy (damage);
}
}
}
Answer by Janick21 · Apr 30, 2020 at 10:53 AM
Through trial and error I got this solution:
Vector 2 mouseposition = Camera.main.ScreenToWorldPoint( new Vector3(Input.mousePosition.x, Input.mousePosition.y, "Distance between your camera and the plane your character is on"));
not the best, but it did work