I'm looking to make it so my fired projectile is shot at the position of the mouse so aiming is an option ie:up down ect..

I have the script working to where it spawns the cloned object and launches it but it only shoots straight from my players hand before disappearing. how can I adjust my command so the object is shot in the direction the mouse is pointing?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ProjectileShooter : MonoBehaviour {
  Transform attachmentPoint;
  GameObject prefab;

  void Start () {

    prefab = Resources.Load ("projectile") as GameObject;   

  // Update is called once per frame
  void Update () {
    if (Input.GetMouseButtonDown (0)) {
      GameObject projectile = Instantiate (prefab) as GameObject;
      projectile.transform.position = attachmentPoint.position + Camera.main.transform.forward * 2;
      Rigidbody rb = projectile.GetComponent<Rigidbody> ();
      rb.velocity = Camera.main.transform.forward * 40;
      Destroy (projectile, 2.5f);
  • 4
    \$\begingroup\$ It would help if we knew more about the context of your game. From the code alone we can't tell if it's top-down, side-on, isometric, over the shoulder, or a half dozen other possibilities. Try including a screenshot, or a diagram of the result you want. A picture can be worth a thousand words in ensuring users trying to help you correctly understand your needs. \$\endgroup\$ – DMGregory Dec 8 '17 at 1:32

You're question is vague, but in general, the solution is to find the vector from the gun (or firing device) to the point where you want it to go. That is your direction vector. You can then normalize it and multiply it by the particle's speed to get a velocity. Something like this:

vec2 directionVec = chosenPoint - gunPoint;
directionVec *= particleSpeed;

This should work in both 2D and 3D. However, in 3D there's an extra step to figure out from the user's click what object they're aiming at. It will involve casting a ray from the camera into the scene and getting a list of objects it intersects. From that list, you need to decide which one the user intended to shoot at. It may be the one nearest the camera, or the one where the angle formed with the player's direction is closest to 0, for example.


The most accurate way is to retrieve the point where to shot based on the mouse position by casting a ray to the scene from the camera

Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, 10000.0f)) {
       Vector3 hitPoint = hit.point;

And then use the hitted point to find the vector based on your player/camera position.

NOTE: Physics.Raycast test only against collider. Any element without a collider will be ignored.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.