- Home /
Need help with my weapon movement script
The script is intended to rotate my Gun on the x angle when I move my mouse horizontal. My script works fine as long MoveOnX is positive, But when its negative, it changes the x, y and z rotation. Can someone help me? ## GunMovement.js ##
public var MoveAmount : float = 1;
public var MoveSpeed : float = 2;
public var GUN: GameObject;
public var CAM: GameObject;
public var MoveOnX : float;
public var MoveOnY: float;
public var DefaultPos : Vector3;
public var DefaultRot : Vector3;
public var NewGunPos : Vector3;
public var NewGunRot : Vector3;
public var ONOff : boolean = false;
function Awake(){
DefaultPos = transform.localPosition;
DefaultRot = transform.localEulerAngles;
ONOff = true;
}
function LateUpdate () {
if(ONOff == true){
MoveOnX = Input.GetAxis( "Mouse X") * Time.deltaTime * MoveAmount;
MoveOnY = Input.GetAxis( "Mouse Y") * Time.deltaTime * MoveAmount;
NewGunPos = new Vector3 ( DefaultPos.x+ MoveOnX, DefaultPos.y + MoveOnY, DefaultPos.z);
NewGunRot = Vector3 ( DefaultRot.x + MoveOnX * 800, DefaultRot.y, DefaultRot.z);
GUN.transform.localPosition = Vector3.Lerp(GUN.transform.localPosition , NewGunPos, MoveSpeed * Time.deltaTime);
GUN.transform.localEulerAngles = Vector3.Lerp(GUN.transform.localEulerAngles , NewGunRot, MoveSpeed * Time.deltaTime);
}
else{
ONOff = false;
GUN.transform.localPosition = Vector3.Lerp(GUN.transform.localPosition, DefaultPos , MoveSpeed *Time.deltaTime);
}
}
For the record: Use code tags (highlight all the code, block by block, and click the "101010" button) when pasting code. It's much appreciated by both those looking to answer your question, and those who had the same question, and are looking to the answers for guidance.
Your whitespace and brackets are very funky, which makes it tricky to read. Code should look at least similar to this (there are lots of different "where brackets go" beliefs, but they should line up somehow)
for ( stuff ) {
do;
}
if ( thing ) {
if ( not another ) {
while ( false ) { print; }
} else {
win;
}
}
When you have something like
}
}
, it can get really tricky to read.
Answer by Akill · Jul 31, 2012 at 08:03 PM
Can you give some background as to why you are doing this? Could your problem possible be solved by parenting your gun to the players camera?
Answer by Loius · Jul 31, 2012 at 08:21 PM
It looks like a gimbal lock issue. Try setting the gun's .rotation to a Quaternion.Euler instead of directly changing its euler angles.
This produces smoother results for me:
NewGunRot.x += MoveOnX * 800; // = Vector3 ( DefaultRot.x + MoveOnX * 800, DefaultRot.y, DefaultRot.z);
//GUN.transform.localPosition = Vector3.Lerp(GUN.transform.localPosition , NewGunPos, MoveSpeed * Time.deltaTime);
GUN.transform.localRotation = Quaternion.Euler( NewGunRot );