- Home /
Script to move an objects position and rotation upon collision with player?
How to implement a script to move an objects position once the player hits the box collider. The way im using this is there is a mask on the ground and the player notices it but there is a room up ahead with a door. Once he's done searching that room up ahead he leaves the room and all of a sudden the mask appears infront of the door and a sound plays. How would I implement this? Thanks.
Answer by sparkzbarca · Nov 13, 2012 at 01:06 PM
OnCollisionEnter(collider other)
is the function that you use to deal with collisions.
you attach a script to the gameobject with the box collider.
other is going to be whatever other collider you collided with. it varies depending on what hit the collider, so first your going to want to check to see if what hit the box was the player.
if(other.tag == "Player")
or something like that.
tags are basically just things added to a gameobject that you add yourself but help you find it.
you might tag enemies with the word "Enemy" and you might tag certain special enemies with "Special Enemy" so you treat them different that normal enemies.
now that you know its the player you'll want to search the scene for the book.
findobjectinscene(gameobject book)
is the function you'll want to use.
lastly you'll want to use the transform component of the book to modify its position and rotation.
book.transform.position controls its position. you'll want to set it to be a little in front of the camera.
you can use
Camera.main.ViewportToWorldPoint(new vector3(.5f,.5f,depth))
.5f, .5f will give you the exact middle of the screen. depth is how far forward from the camera you want the object to be. i'd suggest maybe 2? change it up and find out.
you'll need to rotate the object as well. you can simply make it look at the player or the main camera book.transform.rotation.LookAt(Camera.main)
you can play a sound attached to the book.
book.audio.play()