- Home /
How do I get my character to shoot a projectile in the direction of the cursor?
(EDIT): Ok, I'm creating a 2-d game. I would like my character to be able to shoot projectiles from a spawnpoint in front of him in the direction of the cursor upon clicking on the screen.
I can already spawn the projectile at the spawn point and apply forces to it and make it move. However I do not know how to find the angle for it to shoot at the cursor.
Answers Appreciated.
Answer by MagicoCreator · Dec 30, 2013 at 03:28 AM
you can calculate the direction from which to shoot through simple calculations:
function OnMouseDown(){
var ShootDir : Vector2 = Vector2(Input.mousePosition.x - character.transform.position.x,Input.mousePosition.y - character.transform.position.y)
}
then instantiate your projectile, and either add force to move it with physics, or just move it in that direction
as for charging up:
if you want your shot to charge, while the user is pressing the button:
function Update(){
var timer : float = 0;
var isCharing : boolean = false;
if(isCharging){
timer += Time.deltaTime;
}
}
function OnMouseDown(){
isCharing = true;
}
function OnMouseUp(){
isCharing = false;
//shoot with strenght of timer's value
timer = 0;
}
if you want to just add a simple delay:
function Update(){
var timer : float = 0;
var willShoot : boolean = false;
if(willShoot){
if(timer<0){
//shoot projectile
willShoot = false;
}
else{
timer -= Time.deltaTime;
}
}
}
function OnMouseDown(){
if(!willShoot){
willShoot = true;
timer = 0.5f;
}
}
It didn't work. And not because the typing errors you made (you put "charing" ins$$anonymous$$d of "charging"). On$$anonymous$$ouseDown() only works when clicking a collider. I want to be able to click anywhere and shoot in that direction. So I put the $$anonymous$$ouseDown part in the Update with Input.Get$$anonymous$$ouseButtonDown(), however it still didn't work. After a good hour of fiddling around with it I finally came up with a way of doing it. Thanks for the answer.
Your answer
Follow this Question
Related Questions
Shooting projectiles in 2D world 2 Answers
Network Sync Bullet 2D 0 Answers
How to get rotation for projectile to fire at cursor? 1 Answer
If i click on a object i move to the next level (c#) 0 Answers