I’m working on Abuse-style platformer game on Unity but I got stuck with my mouse aiming mechanic. The link illustrates best what I’m trying to achieve, but the basic idea is to move character around in 2d with keyboard and aim+shoot freely (360 degrees) with mouse, regardless of the walking direction.
I managed to make the bullets fly towards the mouse cursor. Unfortunately the speed of the bullets is relative to mouse’s position also. So even though my bullets go in the right direction when I press the button, they go very slowly if my mouse cursor is closer to my player character and vice versa.
Here’s the code:
#pragma strict
var projectile : Rigidbody;
var projectileSpeed = 130;
var characterOrigin : Vector3;
var targetScreenPos : Vector3;
var targetPosition : Vector3;
var launchVelocity: Vector3;
function Update () {
targetScreenPos = Input.mousePosition;
targetPosition = Camera.main.ScreenToWorldPoint(targetScreenPos);
//center of the character, z-axis is 0 becouse this is 2d game
characterOrigin = Vector3(transform.position.x, transform.position.y, 0);
if (Input.GetMouseButtonDown(0) )
shootPistol();
}
function shootPistol ()
{
var instantiatedProjectile : Rigidbody = Instantiate(projectile, characterOrigin, transform.rotation );
var targetScreenPos = Input.mousePosition;
var targetPosition = Camera.main.ScreenToWorldPoint(targetScreenPos);
var targetDelta = (transform.position - targetPosition) ;
// for some reason I had to invert this to get the bullets to go correctly.
targetDelta *= -1;
launchVelocity = (targetDelta.normalized * projectileSpeed);
// z-axis is 0 becouse this is 2d game
instantiatedProjectile.velocity = Vector3(launchVelocity.x , launchVelocity.y, 0) ;
//so the bullet doesn't collide with the player
Physics.IgnoreCollision(instantiatedProjectile.collider, transform.root.collider);
}
So I guess I need to somehow add/subtract (or multiply/divide?) the distance from mouse to player from the bullet speed, but I’m probably wrong since I’ve been trying to do it for three days without results
I’m having troubles of wrapping my head around Vector3’s and I’m also pretty crappy at programming (even though I love doing it). I hope that someone could point me to the right direction!