- Home /
stop object(door) translation
i am trying to make sliding doors without animation, so i attached this script to the door object(in this case a cube), but i can't figure out how to stop it nor how to move the door to original position when the player is far, how should i do it ?
using UnityEngine; using System.Collections;
public class porte : MonoBehaviour {
public int iDirection;
public int startPos;
public int maxDistance;
Vector3 pos;
Vector3 vel;
protected Transform ThisTransform = null;
protected PlayerController PC = null;
protected Transform PlayerTransform = null;
public float AttackDistance = 10;
protected virtual void Start()
{
GameObject PlayerObject = GameObject.Find ("Player");
PC = PlayerObject.GetComponentInChildren<PlayerController> ();
PlayerTransform = PC.transform;
ThisTransform = transform;
}
void Update() {
float DistanceFromPlayer = Vector3.Distance(transform.position, PlayerTransform.position);
if(DistanceFromPlayer < AttackDistance)
{
transform.Translate(Vector3.right * iDirection * Time.deltaTime);
pos = transform.position;
}
}
}
Answer by TotalAnnihilation · May 22, 2015 at 07:28 PM
Hey! I would do it like this: I only can do java/unityscript, but the idea should be clear.
if(DistanceFromPlayer < AttackDistance %% dooropening)
{
transform.Translate(Vector3.right * iDirection * Time.deltaTime);
pos = transform.position;
if(transform.position > Vector3.right * maxMovement)
dooropening=false;
}
maxMovement being a var maxMovement:int; you declare the maximum Movment of the door. I guess you have to try and error a little.
For sliding back: Not sure if it works, but you could try it
if(DistanceFromPlayer > AttackDistance && doorclosing)
{
transform.Translate((-1)*Vector3.right * iDirection * Time.deltaTime);
if(transform.position < Vector3.right*minMovement)
{
doorclosing = false;
dooropening = true;
}
}
dooropening and doorclosing beeing bools. minMovement same as in the other snippet.
Hope it helped!
unfortunately it says: Operator >' cannot be applied to operands of type
UnityEngine.Vector3' and `UnityEngine.Vector3'
oh yeah, sorry. Just compare the components you are changing, meaning transform.position.x < $$anonymous$$$$anonymous$$ovement or more likely just call $$anonymous$$$$anonymous$$ovement $$anonymous$$Position and set it to a position.
thank you for your help and patience, i am still a noob with unity and i really appreciate yor help
This tutorial is quite good and explains you the basics of this, I think: https://www.packtpub.com/books/content/unity-game-development-interactions-part-1