Shooting to the center of the screen.

Hi,

This code is used to fire laser straight forward.

using UnityEngine;
using System.Collections;

public class LeftGun : MonoBehaviour {

    public Rigidbody laser;
    public AudioClip LaserShot;

    float shotSpeed = 0.1f;
    bool canShoot = true;

    // Update is called once per frame
    void Update () {

        if(!Engine.escape)
        {
            shotSpeed -= Time.deltaTime;

            if(shotSpeed <= 0f)
                canShoot = true;

            if(Input.GetButton("Fire1") && canShoot)
            {
                shotSpeed = 0.1f;
                canShoot = false;
                PlayerGUI.ammunition--;
                audio.PlayOneShot(LaserShot);
                Rigidbody clone = Instantiate(laser,transform.position, transform.rotation) as Rigidbody;
                clone.velocity = transform.TransformDirection(-80, 0, 0);
                Destroy(clone.gameObject, 3);
            }
        }
    }

I would like to fire to the center of the screen (where crosshair is). How can I achive that?

So, you want to fire a laser on a 2D plane toward a crosshair that is always located at the center of the screen. Is that correct?

Something like this:

I’d do something like this:

//
// Screen space (viewport) coordinates are between 0..1 so 0.5 on both the x and y is
// the screen centre.
//
Vector3 screenSpaceCenter = new Vector3(0.5f, 0.5f, 0);
//
// Convert that to a world point where myCamera needs to be changed to be
// your actual camera.
//
Vector3 laserEnd = myCamera.ViewportToWorldPoint(screenSpaceCenter);

//
// Shoot towards laserEnd
//
2 Likes

That solution will be adequate if the projectiles always go to the center of the screen and the spaceship doesn’t move. If it does move and the lasers go to a point in front of it rather than a static position at the center of the screen that solution will not work.

Yeah… It’s not working. Like outwarddesign said, spaceship is moving and it’s not working.

@
Solved.

public Camera myCamera;

float x = Screen.width / 2;
float y = Screen.height / 2;
              
var ray = myCamera.ScreenPointToRay(new Vector3(x, y, 0));
clone.velocity = ray.direction * 80;
2 Likes

Looks good. Good job!

thanks worked

thx it worked thx soooooo much