- Home /
Fire object towards mouse cursor
This has been a frustrating issue for quite a while now. I have been doing heavy research on the subject and all I come up with is some very inefficient code that usually displays 10 or more warnings. I am currently using the Unity Documentation code that they provided, which does not work... What I want to do is to instantiate an object and fire it towards my cursor point, only to stop when colliding with another object. The unity code is here:
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {
public GameObject particle;
void Update() {
if (Input.GetButtonDown("Fire1")) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray)) {
Instantiate(particle, transform.position, transform.rotation) as GameObject;
}
}
}
}
Please help me with this issue as soon as possible. Thanks in advance! :D
Answer by Fr0stbite · Feb 08, 2014 at 02:54 PM
make a script for the particle
//moveToVector.Js
#pragma strict
var endingPoint : Vector3;
var speed : float = 1000;
function Start () {
}
function Update () {
transform.rotation = Quaternion.Slerp(transform.rotation,
Quaternion.LookRotation(endingPoint - transform.position), 50*Time.deltaTime);
transform.position = Vector3.MoveTowards(transform.position, endingPoint, speed*Time.deltaTime);
}
and here is your script(sorry i use only JS):
function Update(){
if(Input.GetKeyDown(KeyCode.Mouse0))
{
var hit: RaycastHit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, hit)) {
var clone = Instantiate(particle, transform.position, transform.rotation)
clone.GetComponent(moveToVector).endingPoint = hit.point;
}
}
}
Thanks! :D
I managed to convert it to C# and it works like a charm!
Thank you so much :D :D
Your answer
Follow this Question
Related Questions
Firing projectile towards mouse position from player... 0 Answers
Firing towards mouse- aim in all directions? 1 Answer
A node in a childnode? 1 Answer