x


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

more ▼

asked Apr 06 '10 at 09:12 AM

alex 1 gravatar image

alex 1
89 13 13 19

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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.

more ▼

answered Apr 06 '10 at 12:08 PM

duck gravatar image

duck ♦♦
40.9k 92 148 415

Thanks a bunch Duck!

Apr 06 '10 at 12:35 PM alex 1
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x5056
x1865
x801
x100

asked: Apr 06 '10 at 09:12 AM

Seen: 1551 times

Last Updated: Apr 06 '10 at 09:12 AM