Hey guys,
I am having a problem in my script where I want let the player open a drawer by using the mouse. The drawer then moves outward depending on the speed of the mouse Y movement. Everything works fine when the drawer object is aligned to the global x axis. My problem is that I don’t want it to move on the global x axis but instead on its own local x axis.
As you can see the drawers local x axis is pointing away from the cube - The drawer on the left has the x axis pointing out the same way but the only one that works is the one in the middle which is aligned with the global x axis. The other one doesn’t even move at all. They are both exactly the same but have different rotations.
The code:
#pragma strict
var startDistance :float;
var endDistance : float;
var axisInverted : boolean;
private var startPoint : Vector3;
private var endPoint : Vector3;
private var endPosition : Vector3;
private var startPosition : Vector3;
private var lockedPosition : Vector3;
function Start(){
lockedPosition = Vector3(transform.localPosition.x,transform.localPosition.y,transform.localPosition.z);
if(!axisInverted){
startPoint = transform.localPosition - transform.InverseTransformDirection(Vector3.right)*(startDistance-.01);
startPosition.x = startPoint.x;
endPoint = transform.localPosition + transform.InverseTransformDirection(Vector3.right)*endDistance;
endPosition.x = endPoint.x;
}
else{
startPoint = transform.localPosition - transform.InverseTransformDirection(Vector3.left)*(startDistance-.01);
startPosition.x = startPoint.x;
endPoint = transform.localPosition + transform.InverseTransformDirection(Vector3.left)*endDistance;
endPosition.x = endPoint.x;
}
}
function Update () {
transform.localPosition = Vector3(transform.localPosition.x,lockedPosition.y,lockedPosition.z);
var moveSpeed = Input.GetAxis("Mouse Y");
if(!axisInverted){
if(Input.GetButton("Use")){
rigidbody.AddRelativeForce(-Vector3.right*moveSpeed,ForceMode.Impulse);
}
if(transform.localPosition.x >= startPoint.x){
rigidbody.velocity = Vector3.zero;
transform.localPosition.x = transform.localPosition.x - 0.01;
}
if(transform.localPosition.x <= endPoint.x){
rigidbody.velocity = Vector3.zero;
transform.localPosition.x = transform.localPosition.x + 0.01;
}
}
else{
if(Input.GetButton("Use")){
rigidbody.AddRelativeForce(-Vector3.left*moveSpeed,ForceMode.Impulse);
}
if(transform.localPosition.x <= startPoint.x){
rigidbody.velocity = Vector3.zero;
transform.localPosition.x = transform.localPosition.x + 0.01;
}
if(transform.localPosition.x >= endPoint.x){
rigidbody.velocity = Vector3.zero;
transform.localPosition.x = transform.localPosition.x - 0.01;
}
}
}
I hope you understand what I am trying to do and it would be great if you could check the code. It should all be set for local coordinates but I may have missed something.