*EDIT: Working code:
using UnityEngine;
using System.Collections.Generic;
public class WeaponSway : MonoBehaviour {
public float moveAmount = 50f;
public float moveSpeed = 2f;
public float maxMoveAmount = 100f;
public GameObject gun;
public GameObject firePoint;
private float moveOnX;
private float moveOnY;
private Vector3 defaultPOS;
private Vector3 newPOS;
public bool aiming = false;
public Vector3 hipPOS;
public Vector3 aimPOS;
void Start() {
defaultPOS = transform.localPosition;
}
void Update() {
if (Input.GetKeyDown (KeyCode.Mouse1)) {
if (firePoint.GetComponent<TestGun>().aiming) {
firePoint.GetComponent<TestGun>().aiming = false;
}
else {
firePoint.GetComponent<TestGun>().aiming = true;
}
}
if (firePoint.GetComponent<TestGun>().aiming) {
defaultPOS = aimPOS;
}
else {
defaultPOS = hipPOS;
}
moveOnX = Input.GetAxis("Mouse X") * moveAmount;
moveOnY = Input.GetAxis("Mouse Y") * moveAmount * 1.5f;
if (moveOnX > maxMoveAmount) {
moveOnX = maxMoveAmount;
}
if (moveOnX < maxMoveAmount *-1) {
moveOnX = maxMoveAmount *-1;
}
if (moveOnY > maxMoveAmount) {
moveOnY = maxMoveAmount;
}
if (moveOnY < maxMoveAmount *-1) {
moveOnY = maxMoveAmount *-1;
}
RaycastHit hit;
newPOS = new Vector3 (defaultPOS.x+moveOnX, defaultPOS.y+moveOnY, defaultPOS.z);
Debug.DrawRay (transform.position, transform.forward, Color.blue);
if (Physics.Raycast(transform.position, transform.forward, out hit, 1.5f)) {
newPOS.z+=(Vector3.Distance(transform.position, hit.point)*-1);
}
gun.transform.localPosition = Vector3.Lerp(gun.transform.localPosition, newPOS, moveSpeed*Time.deltaTime);
}
}