- Home /
Tap Where To Shoot 2D
Hey guys, Kind of stuck on this. How would you write a javascript that allows you to tap where you want to shoot in 2D? I assume that you'd make the player look at where you touch using Transform.LookAt and then instantiate a projectile traveling forward.
I wrote a script that should make the player look at the finger touch but it doesn't work. When the screen is touched the object disappears.
function Update () {
for (var i = 0; i < Input.touchCount; ++i) {
if (Input.GetTouch(i).phase == TouchPhase.Began) {
var finger : Vector2 = Input.GetTouch(i).position;
transform.LookAt(finger);
}
}
}
And that's where I'm stuck. Thanks for the help.
Comment
Best Answer
Answer by YikYikHeiHei · Jul 28, 2011 at 01:45 AM
It is rotate XZ.
var rotateSpeed = 7.0;
function FixedUpdate()
{
for (var touch : Touch in Input.touches)
{
var playerPlane = new Plane(Vector3.up, transform.position);
var ray = Camera.main.ScreenPointToRay (touch.position);
var hitdist = 0.0;
if (playerPlane.Raycast (ray, hitdist))
{
var targetPoint = ray.GetPoint(hitdist);
var targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotateSpeed * Time.deltaTime);
}
}
}