- Home /
Move object when player reach trigger
Hello.. I'm noob in scripting. It might be a simple script, but I totally noob :v first here is my 2D game scene
So I want to make my object "Curtain" to move down to the terrain automatically when the "player" reach the "boxtrigger".
So far I add this code to my curtain object and it moved to the targeted terrain but only when every I start the game.
using UnityEngine;
using System.Collections;
public class Movement2 : MonoBehaviour {
public Transform Target;
public float MoveToSpeed;
private Transform _transform;
private void Start()
{
_transform = transform;
}
private void FixedUpdate()
{
_transform.position = Vector3.MoveTowards(_transform.position, Target.position, MoveToSpeed);
}
}
So how do I make "Boxtrigger" as I trigger to move "Curtain" when my player reach it?
Answer by dvora · Aug 17, 2014 at 10:30 PM
Try this:
public var _cutrain : GameObject;
public var _moveposition : Transform;
public var speed : float;
function OnTriggerEnter(other : Collider){
_curtain.transform.position= Vector3.Lerp(_curtain.transform.position,_moveposition.position, Time.deltaTime * speed);
}
Attach this JavaScript to the box collider
After I read documentation link from Alessio89 below, I notice that I use 2D box collider in both player and the triggerbox.. so i put :
public var _cutrain : GameObject;
public var _moveposition : Transform;
public var speed : float;
function OnTriggerEnter2D(other : Collider2D){
_curtain.transform.position= Vector3.Lerp(_curtain.transform.position,_moveposition.position, Time.deltaTime * speed);
}
and the code works.. thx :)
Answer by Alessio89 · Aug 17, 2014 at 04:46 PM
You should read about Colliders and how they can function as Triggers. Then what you want to do, is to get the curtain object from the box trigger script. To do this you use GameObject.Find. Once you have the reference for the curtain in your trigger script, you can get the "Movement2" component from the curtain's reference with GetComponent and make the curtain move.
Hope it was clear, I linked to the scripting API so you can see or yourself how these things are achieved. :)