- Home /
Fire ball towards touch position
Hello
I'm trying to fire a ball from a cube at touch position
I have this script. It does fire when I touch the screen but always in the same direction. Not towards the touch position but simple upwards.
Here is the script
using UnityEngine;
using System.Collections;
public class Fire : MonoBehaviour
{
public Rigidbody SpherePrefab;
public Transform barrelEnd;
// Use this for initialization
void Start () {
}
// Use this for initialization
void Update ()
{
int fingerCount = 0;
foreach (Touch touch in Input.touches) {
if (touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled)
fingerCount++;
if (fingerCount > 0){
Vector3 worldPoint = Camera.main.ScreenToWorldPoint(touch.position);
Vector2 touchPos = new Vector2(worldPoint .x, worldPoint.y);
transform.LookAt(touchPos);
Rigidbody rocketInstance;
rocketInstance = Instantiate(SpherePrefab, touchPos, Quaternion.identity) as Rigidbody;
rocketInstance.AddForce(barrelEnd.forward * 7000);
}
}
}
}
Any help will be appreciated since I am stuck here and can't finish my game
Thanks
Answer by Armand · Jul 09, 2014 at 11:50 AM
You are firing into the direction of barrelEnd, which doesn't seem to change based on the touch position. Try replacing transform on line 26 to barrelEnd?
I sincerely have to ask you how to do that because I did try and but is not possible . It doesn't even compile Any idea how? Thanks anyway for the answer
Hmm, are you sure it was the right line? If all the code you showed is in the same script, it should work. Did the code compile before the change? And you didn't change anything else, or make typos? Which error does the console give?
Hello again
This is what i did add
int fingerCount = 0;
foreach (Touch touch in Input.touches) {
if (touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled)
fingerCount++;
if (fingerCount > 0){
Vector3 worldPoint = Camera.main.ScreenToWorldPoint(touch.position);
Vector2 touchPos = new Vector2(worldPoint .x, worldPoint.y);
transform.LookAt(touchPos);
Rigidbody rocketInstance;
rocketInstance = Instantiate(Sphere, touchPos, Quaternion.identity) as Rigidbody;
rocketInstance.transform.LookAt(touchPos);
rocketInstance.AddForce(barrelEnd.forward * 7000);
}
I add a line as you might see. I did compile but it still just the same fire upwards not the position of the touch.
I gently ask you if you can be more specific.
Thanks alot for taking the time to asnwer me
CL