- Home /
Parenting player to car on click.
I am creating a game which I would like the player to be able to click a vehicle/car they would like to get in.
So I know the code
player.parent = vehicle;
will attach them, but how do I say that If the player clicks on the object, the player will parent with the vehicle and ALSO change the smooth follow script to the vehicle instead of the player?
Thanks
Answer by duck · Apr 06, 2010 at 12:08 PM
To detect clicks on an object, the object must have a Collider Component. You can then use the OnMouseDown or OnMouseUp event handler functions.
The "SmoothFollow" script which comes in Unity's Standard Assets package has a public variable defined as:
var target : Transform;
Which means you can set this variable from any external source.
So, combining all these together would give you something that might look like this. If this script is placed on the vehicle, you can use the variable "transform" to refer to the object's own transform. This script also assumes there's only one instance of "SmoothFollow" in your scene.
function OnMouseUp() {
player.parent = transform;
FindObjectOfType(SmoothFollow).target = transform;
}
If your player isn't in the correct position when you click on the vehicle, it will stay in that relative position once parented, so you might want to set the player's localPosition to correct this, after parenting it to the vehicle.
Your answer
Follow this Question
Related Questions
How To Stop Player Completely? 1 Answer
HoverCraft physics error 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Quake like movement 1 Answer
How do I make a first person player get in a vehicle? 0 Answers