Home > front end >  Only move the "z" axis
Only move the "z" axis

Time:06-09

I have this Recoil script, the only problem is that the code moves my gun to all of the axes but I only want to move my gun on the Z-axis. I couldn't find any solution for it. Thanks! Here is the code:

 using UnityEngine;
 using System.Collections;
 
 public class Recoil : MonoBehaviour {
 
     public Vector3 hipPos;
     public Vector3 zoomPos;
     public float speed = 4f;
 
     void Update () {
         if(Input.GetMouseButton(0)) {
             transform.localPosition = Vector3.Lerp(transform.localPosition, zoomPos, Time.deltaTime * speed);
             transform.localPosition = Vector3.Lerp(transform.localPosition, hipPos, Time.deltaTime * speed);
         }
         else {
             transform.localPosition = Vector3.Lerp(transform.localPosition, hipPos, Time.deltaTime * speed);
         }
     }
 }

CodePudding user response:

Get the gun to move towards the desired z position, but keep the x and y positions the same.

 using UnityEngine;
 using System.Collections;
 
 public class Recoil : MonoBehaviour {
 
     public Vector3 hipPos;
     public Vector3 zoomPos;
     public float speed = 4f;
     private Vector3 localPosition 
 
     void Update () {
         if(Input.GetMouseButton(0)) {
             transform.localPosition = Vector3.Lerp(transform.localPosition, new Vector3(transform.localPosition.x, transform.localPosition.y, zoomPos.z), Time.deltaTime * speed);
             transform.localPosition = Vector3.Lerp(transform.localPosition, new Vector3(transform.localPosition.x, transform.localPosition.y, hipPos.z) , Time.deltaTime * speed);
         }
         else {
             transform.localPosition = Vector3.Lerp(transform.localPosition, new Vector3(transform.localPosition.x, transform.localPosition.y, hipPos.z), Time.deltaTime * speed);
         }
     }
 }

To understand how lerp works, refer to the Unity documentation for it here.

  • Related