- Home /
How do I make an Instantiated Projectile travel towards Center of Screen
I'm using this code to instantiate a projectile and get it to travel forward.
function Update ()
{
if(Input.GetButtonDown("Fire1"))
{
var starburstInstance : Rigidbody;
starburstInstance = Instantiate(starburstPrefab, starburstGunEnd.position, starburstGunEnd.rotation);
starburstInstance.AddForce(starburstGunEnd.forward * 2500);
audio.PlayOneShot(starburst);
}
}
All was fine until I added a hide cursor and add crosshair script. Now I suddenly realise that my targeting/aiming is way off. How can I change (or replace) this line of code so the object will effectively travel towards where the crosshair was positioned and not just directly forwards?
starburstInstance.AddForce(starburstGunEnd.forward * 2500);
(Crosshair is positioned in center screen, attached to main camera)
Any ideas guys???
This is how I would do that:
var target = new GameObject();
target.transform.position = Camera.main.ScreenToViewportPoint(new Vector3(Screen.width/2,Screen.height/2,0));
starburstGunEnd.LookAt(target.transform);
starburstInstance.AddForce(starburstGunEnd.forward * 2500);
audio.PlayOneShot(starburst);
I've just made a few corrections to the below - basing on these output errors.
Answer by Digital-Phantom · Jan 01, 2015 at 08:03 AM
Getting the following errors
Assets/Scripts/InstantiateReaperDisc.js(14,78): BCE0017: The best overload for the method 'UnityEngine.Camera.ScreenToViewportPoint(UnityEngine.Vector3)' is not compatible with the argument list '(int, int)'.
Assets/Scripts/InstantiateReaperDisc.js(15,39): BCE0023: No appropriate version of 'UnityEngine.Transform.LookAt' for the argument list '(UnityEngine.GameObject)' was found.
???
Your answer
Follow this Question
Related Questions
Rotation problem with spawning bullet 2 Answers
AddForce not working on instantiated bullets 1 Answer
AddForce on Prefab has inconsistent behaviour. 1 Answer
Jump Force gets added up with repeated input and causes character to fly off 0 Answers
Trying to move an instantiated object with a Rigidbody2D and AddForce 1 Answer