- Home /
Please help me convert this script from using position to rotation?
Hi. I am working on a script that gives my FPS weapon a more realistic 'sway' effect:
In this script I have used the mouse input and localPosition to create the effect...
var speed : float = 1;
var maxAmount : float = 1;
private var newPos : Vector3;
private var localPos : Vector3;
private var movementX : float;
private var movementY : float;
function Start(){
localPos = transform.localPosition;
}
function Update (){
movementX = Input.GetAxis("Mouse X") * Time.deltaTime * maxAmount;
movementY = Input.GetAxis("Mouse Y") * Time.deltaTime * maxAmount;
newPos.x = localPos.x - movementX;
newPos.y = localPos.y - movementY;
newPos.z = localPos.z;
transform.localPosition = Vector3.Lerp(transform.localPosition,newPos,speed*Time.deltaTime);
}
I have decided that changing the position of the object isn't the right way to create a realistic effect. I have tried to use localRotation and Quaternion like this...
var speed : float = 1;
var maxAmount : float = 1;
private var newRot : Quaternion;
private var localRot : Quaternion;
private var movementX : float;
private var movementY : float;
function Start(){
localRot = transform.localRotation;
}
function Update (){
movementX = Input.GetAxis("Mouse X") * Time.deltaTime * maxAmount;
movementY = Input.GetAxis("Mouse Y") * Time.deltaTime * maxAmount;
newRot.x = localRot.x - movementX;
newRot.y = localRot.y - movementY;
newRot.z = localRot.z;
transform.localRotation = Quaternion.Lerp(transform.localRotation,newRot,speed*Time.deltaTime);
}
This script doesn't have any effect of the weapon, it just stays 'static', even if I crank the speed up to 999. So can someone please help me with this problem? - Thanks
Try using the euler angles ins$$anonymous$$d (`transform.localEulerAngles`).
Its best to 'read' the local euler, dont expect necessarily realistic results by manipulating it directly. If you can use Euler Angles (tho quaternions can be a headache in and of themselves!)
If you are unsure of the difference, i mean
Quaternion.Euler(....
Granted localEuler will give you some kind of result, you will find out the hard way: when you reach a limit, it will no longer respond correctly.
Could you please show me how to implement this into my script? - I am not a genius...
Try thinking outside the box. Presumably you created your weapon in some 3d-modelling tool? If it has animations for firing etc, why not make a 'movement sway' animation, too? This way, you can make it look good and realistic, and you won't have to worry about any complex quaternion arithmetic to achieve the desired effect.
Once you've done that, just play the animation at a speed dependent on the player's movement rate, and you're all set.