Tap to shoot 2d (please help)
Hey, so I'm new to here and I have a question - I got this nice code for touchscreen devices which gets the finger coordinates and after that shoots projectile at the touched place. The problem is, that the speed of bullet that it shoots out depends on how close you tap from the bullet source (in code "barrelEnd"). The scene is set up in isometric style (2d). I guess something has to be done with AddForce. Gravity is set to 0 so its not affected by the distance. I already tried velocity. The bullet is slow if tapped near gun, but fast if tapped away from gun. The code for shooting:
using UnityEngine;
using System.Collections;
public class ShootBullet : MonoBehaviour
{
public Rigidbody2D bullet;
public Transform barrelEnd;
void Start () {
}
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);
Rigidbody2D rocketInstance;
rocketInstance = Instantiate(bullet, touchPos, Quaternion.identity) as Rigidbody2D;
rocketInstance.transform.LookAt(touchPos);
rocketInstance.AddForce(barrelEnd.forward * 7000);
}
}
}
}
Addforce
is physic force that's mean the bullet will go down after specific distance depending on the Addforce speed and the mass of the bullet. if you want a constant speed use Rigidbody2D.velocity
Gravity is set to 0 so its not affected by the distance. I already tried velocity. The bullet is slow if tapped near gun, but fast if tapped away from gun.