Tap Where To Shoot 2D
Asked Answered
P

1

0

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.

Pelerine answered 27/2, 2024 at 23:17 Comment(0)
P
0

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);
        }
    }
}
Postexilian answered 27/2, 2024 at 23:17 Comment(1)

That's freakin perfect Thank you so much

Pelerine

© 2022 - 2025 — McMap. All rights reserved.