- Home /
How do you shoot a 2d projectile at any angle from your character?
I am trying to shoot a fireball from my character where I click my mouse. When I click what I want to happen is a fireball will spawn at my character and travel (and rotate) towards where I clicked my mouse. Does anyone know a good way to do this?
With my current implementation I have a very strange bug. It only shoots fireballs at the correct location when I'm standing at (0,0). If I am standing somewhere else it shoots very off target, or even in the completely wrong direction...
Just hoping someone knows a good way to do this!
protected virtual void Update() {
//CLICK TO MOVE
if (shooting) {
canWalk = false;
if (Input.GetMouseButtonDown(0)) {
Plane playerPlane = new Plane(Vector3.forward, transform.position);
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
if (!EventSystem.current.IsPointerOverGameObject()) {
toMove = true;
} else {
toMove = false;
}
targetPosition = cam.ScreenToWorldPoint(Input.mousePosition);
Debug.DrawRay(ray.origin, ray.direction * 500, Color.yellow);
float hitdist = 0.0f;
if (playerPlane.Raycast(ray, out hitdist) && toMove) {
targetPosition = ray.GetPoint(hitdist);
Debug.Log(targetPosition);
//Instantiate(point, targetPosition, Quaternion.identity);
targetPosition.z = transform.position.z;
Vector3 location = new Vector3(transform.position.x, transform.position.y, transform.position.z);
GameObject beam = Instantiate(Projectile, location, Quaternion.identity) as GameObject;
beam.transform.position = Vector3.MoveTowards(beam.transform.position, targetPosition, Time.deltaTime * 100);
beam.GetComponent<Rigidbody2D>().velocity = beam.transform.TransformDirection(new Vector3(targetPosition.x, targetPosition.y, lookVec.z));
shooting = false;
return;
}
}
Your answer
Follow this Question
Related Questions
Need some help with firing projectile at player using Rigidbody Velocity 1 Answer
instantiate finding upstream velocity 1 Answer
Projectile Trajectory Velocity, with predefined Start and End Positions 0 Answers
How to calculate the speed and direction to intercept with a target 1 Answer
Shoot Projectile on the direction of where the gun is facing 1 Answer