- Home /
How do I make a gun aim down sights?
I have a problem where a script that is just supposed lerp the gun object between a hip and zoomed firing position isn't working at all.
using UnityEngine;
using System.Collections;
public class GunZoom : MonoBehaviour {
public Vector3 hipPos;
public Vector3 zoomPos;
void Update () {
if(Input.GetButton("Zoom")) {
transform.localPosition = Vector3.Lerp(transform.localPosition, zoomPos, Time.deltaTime);
}
else {
transform.localPosition = Vector3.Lerp(transform.localPosition, hipPos, Time.deltaTime);
}
}
}
The "Zoom" button is just the right mouse button. When I click it, nothing happens. The gun is a child of the camera, which is a child of the player object. Any ideas?
Answer by FortisVenaliter · Aug 21, 2015 at 08:29 PM
Well, Time.deltaTime in that lerp may be a bit slow. Even when you hold the button down, does it move?
No, it doesn't move at all. I did try it with some random other values too, and nothing seemed to make any difference.
Just a few things to check then, because that code looks pretty good to me...
You have set both the hipPos and zoomPos to be different values in the inspector in Unity, correct?
You haven't modified the Time.timeScale variable, have you?
Try using Time.deltaTime*10 and see if that makes a difference.
Are you sure the button Zoom is set up right? which object the script is attached to? The script works fine here apart of the slow motion which could be fixed easily with speed * Time.deltaTime . But let's stay at the original issue for now.
Yes, they are different values. No, I haven't modified that variable. No, that didn't change anything.
And yes Positive7 it is set up right. I've put some debug.logs into the first if statement and they've all run.
Answer by allenallenallen · Aug 21, 2015 at 09:23 PM
Don't know how you set up the animation so you have to figure out that part on your own.
But what I do know is that you used Vector3.Lerp wrong.
Vector3.Lerp works like percentage of completion. You can't put Time.deltaTime there because it wouldn't make any sense.
When it's 0, the object is at its original position.
When it's 1, the object is at the destination.
When it's 0.5, the object is half way between the original position and destination.
Yes, you can. It works fine as long as Time.deltaTime is less than 1. It's not the best practice by any means, but for prototyping, it works great.
Answer by MiniMe_ · Aug 22, 2015 at 03:51 PM
Instead of using Vector3.Lerp use Vector.MoveTowards
It also gives the gun a more snap to response than still slowly moving when ADS.