Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Weapon Sync to camera

Discussion in 'Game Design' started by WoobatPlays, Jan 30, 2022.

  1. WoobatPlays

    WoobatPlays

    Joined:
    Jan 30, 2022
    Posts:
    1
    I am new to unity and want to make an FPS game. I want the gun to be synced to the camera like in most FPS games where if you look up, the gun moves up with you. I tried using some code(attached to the camera):
    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class MouseLook : MonoBehaviour
    7. {
    8.  
    9.     public float mouseSensitivity = 100f;
    10.  
    11.     public Transform playerBody;
    12.     public Transfomr playerWeapon;
    13.  
    14.     float xRotation = 0f;
    15.  
    16.     // Start is called before the first frame update
    17.     void Start()
    18.     {
    19.         Cursor.lockState = CursorLockMode.Locked;
    20.     }
    21.  
    22.     // Update is called once per frame
    23.     void Update()
    24.     {
    25.         float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
    26.         float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
    27.  
    28.         xRotation -= mouseY;
    29.         xRotation = Mathf.Clamp(xRotation, -90f, 90f);
    30.  
    31.         transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
    32.         playerBody.Rotate(Vector3.up * mouseX);
    33.         playerWeapon.Rotate(Vector3.left * mouseY);
    34.     }
    35. }
    36.  
    but all that did was rotate the gun in sync with the camera, not move it. If anyone is willing to help fix this or explain how it works than I would be very grateful!
     
  2. Ed_Muel

    Ed_Muel

    Joined:
    Mar 16, 2017
    Posts:
    51
    Have you tried just attaching the gun to the camera, then they should move at the same time.