Donnerstag, 3. Mai 2012

Unity3D: 3rd Person Shooter Camera

I reviewed and updated this C# script from the Unity3D 3rdPersonShooter project, so you can just add it to your camera and drag your player onto the "player" variable and thats it. You don't need to do anything other. Originally there was support for a crosshair and an xbox (or another) controller with two joysticks - you can activate that by uncommenting some stuff. It is described there.

public Transform player;
// public Texture crosshair; // crosshair - removed it for quick and easy setup. ben0bi
// if you add the crosshair, you need to drag a crosshair texture on the "crosshair" variable in the inspector

protected Transform aimTarget; // that was public and a gameobject had to be dragged on it. - ben0bi

public float smoothingTime = 10.0f; // it should follow it faster by jumping (y-axis) (previous: 0.1 or so) ben0bi
public Vector3 pivotOffset = new Vector3(0.2f, 0.7f, 0.0f); // offset of point from player transform (?) ben0bi
public Vector3 camOffset = new Vector3(0.0f, 0.7f, -3.4f); // offset of camera from pivotOffset (?) ben0bi
public Vector3 closeOffset = new Vector3(0.35f, 1.7f, 0.0f); // close offset of camera from pivotOffset (?) ben0bi

// Do a raycast from the camera to find the distance to the point we're aiming at.
float aimTargetDist;
if (Physics.Raycast(cam.position, cam.forward, out hit, 100, mask)) {
aimTargetDist = hit.distance + 0.05f;
}
else {
// If we're aiming at nothing, keep prev dist but make it at least 5.
aimTargetDist = Mathf.Max(5, prevDist);
}

// Set the aimTarget position according to the distance we found.
// Make the movement slightly smooth.
aimTarget.position = cam.position + cam.forward * aimTargetDist;
}

// so you can change the camera from a static observer (level loading) or something else
// to your player or something else. I needed that for network init... ben0bi
public void SetTarget(Transform t)
{
player=t;
}

Hi. I'm a little bit curious here. What if the player or the character that going to be followed by the camera is instantiated first. I can't drag the character prefab that's not in the scene to the script.