- Home /
Looking and firing towards mouse position, 2d game.
I am making a 2d game where I need my player to fire towards my mouse position when the space key is pressed. I already have the shooting that works, but the aiming towards the mouse is where I get stuck.
Thank you very much for your help!
using UnityEngine;
using System.Collections;
public class PlayerShooting : MonoBehaviour
{ public GameObject bulletPrefab;
public Transform bulletSpawn;
public float coolDown = 3f;
void Update ()
{
//print ("the cooldown time is " + coolDown);
CoolDownTimer();
if(coolDown <= 0)
{
if(Input.GetKeyDown(KeyCode.Space))
{
Instantiate(bulletPrefab,bulletSpawn.position,bulletSpawn.rotation);
coolDown = 1f;
}
}
}
void CoolDownTimer()
{
coolDown -= Time.deltaTime;
}
}
Answer by revolute · Feb 13, 2015 at 07:05 AM
Try this : Camera.main.ScreenToWorldPoint(Input.mousePosition);
Any camera is fine.
Answer by rezki · Feb 13, 2015 at 07:07 AM
use the Transform.LookAt for the bulletSpawn
and check out Input.mousePosition it's a Vector2
Answer by Anindya-Nishant · Feb 13, 2015 at 10:32 AM
destination = Camera.mainCamera.ScreenToWorldPoint (Input.mousePosition); destination.z = 0;
direction = destination - yourPlayer.transform.position;
where destination is variable which holds the mouse position. Hope it will work.
Your answer
Follow this Question
Related Questions
Problem with gun rotation after flipping character (2D) 1 Answer
Shooting around defense position without contact 1 Answer
Shooting at an object 2 Answers
Bullet disappears for no reason 2 Answers
How do I get 2D Soldat-style camera movement/aiming? 0 Answers