spaceship aim

I want to rework the aim system of my game because i’m not satisfied at all with the current one.
This is what I want to achieve : [Unity 4] Locking mouse to the centre of the screen (JavaScript) - YouTube
And what I have now : https://dl.dropboxusercontent.com/u/25407702/flyingship/FlyingShip.html (W, A, S, D to move , LeftShip for boost,
1 /2 to switch between machine gun and rail gun)

At first i wanted a 3D crosshair so I put mine on a plane and tried to align it with the bullet impact. But I can’t get greats results, at some correct distances it works nicely, but at close or long range, impacts are not in the center of my crosshair.
So i want to rework it like on the youtube’s video, but can’t think of the right way to do it.

I think i need to render my crosshair on the GUI and follow the mouse, but for projectiles going where i’m aiming, I’m stuck.

Projet’s github : GitHub - Frolanta/FlyingShipProject: multiplayer spaceshooter game with UNity3D (If you interested)

Thanks.

You can use the GUITexture object for your crosshair and a raycast to find out where the shots will land. Then simply convert the raycast’s hit to viewport space and place the crosshair there.

public var muzzle : Transform;
public var crosshair : Transform;
public var viewport : Camera;

public var maxDistance : float = 1000;

function Update () {

	var ray : Ray = new Ray(muzzle.position,muzzle.forward);
	var hit : RaycastHit;
	if (Physics.Raycast(ray,hit,maxDistance)) {
		crosshair.position = viewport.WorldToViewportPoint(hit.point);
		}
	else {
		crosshair.position = viewport.WorldToViewportPoint(muzzle.forward * maxDistance);
		}

     }

“muzzle” should be an empty gameObject that is aligned to the origin of your shots. “crosshair” should be a GUITexture object. “viewport” will be a camera. “maxDistance” is the length of the ray. if the target is too far, the crosshair will be set at maxDistance.

For mouse aiming, it’s a bit different.

public var ship : Transform;
public var crosshair : Transform;
public var viewport : Camera;

public var maxDistance : float = 1000;

function Update () {

	var ray : Ray = viewport.ScreenPointToRay(Input.mousePosition);
	var hit : RaycastHit;
	if (Physics.Raycast(ray,hit,maxDistance)) {
		crosshair.position = viewport.WorldToViewportPoint(hit.point);
		ship.LookAt(hit.point);
		}
	else {
		crosshair.position = viewport.WorldToViewportPoint(muzzle.forward * maxDistance);
		ship.LookAt(muzzle.forward * maxDistance);
		}

	}

“ship” is the transform of your player. The other variables are the same as before. This does much the same as before, except that the ray originates from the camera towards the mouse position and the ship locks onto the point indicated by the raycast.

Both methods have the added advantage of the crosshair NOT scaling relative to the distance. It will always stay the same size.