Search code examples
unityscriptunity-game-engine

Not able to Shoot in the direction of the hand


I have designed a model in blender and imported in Unity and applied ThirdPersonController, ThirdPersonCharacter, ThirdPersonUserControl on it and got animation y following the guidelines, now i have created a script for shooting the bullets and attached it to the rigged hand/gun. But whenever i click "Fire1" the bullet is getting shooted in other direction..

I want when i move the mouse, the hand should move in the direction of the mouse + body should rotate in the direction of the mouse (if on backside) and when i left click, it should fire a bullet in the direction of the mouse(one at a time).

Video for better understanding - http://tinypic.com/r/34yohli/9

I tried a script, but its not following the way i want.

Shoot.js

#pragma strict   var projectile : GameObject;
var fireRate = 0.5;
private var nextFire = 0.0;
var shotDelay = .5;

function Update ()
{
    if (Input.GetButton ("Fire1") && Time.time > nextFire) 
    {
        nextFire = Time.time + fireRate;
        var clone = Instantiate (projectile, transform.position, transform.rotation);

    }
}

MouseMovement.cs

using UnityEngine;
using System.Collections;

public class MouseMovement : MonoBehaviour
{

    public float speed = 1.5f;
    private Vector3 target;

    void Start()
    {
        target = transform.position;
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            target.x = transform.position.x;
        }
        transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
    }
}

Solution

  • To detect the movement of the mouse you should use the Input.GetAxis("Mouse X") or Input.GetAxis("Mouse Y"). If you want the camera to move with the character you can set it as a child of the character. You can check the MouseLook Script for more info.