Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Bug child relative to camera position

Discussion in 'Scripting' started by Nagonn, Oct 5, 2023 at 4:57 AM.

  1. Nagonn

    Nagonn

    Joined:
    Sep 21, 2023
    Posts:
    3
    didn't know what other forum to ask so I am putting this here:

    I have a game object that has a laser shoot out of its position to where I am looking with the camera in a fps game. As it is a child of the player it moves with the player, but the player itself doesn't rotate with the camera, only the camera looks around. the shoot point is bottom right if I don't look around, but if I turn around its bottom left.

    pretty please help me rotate the shooting point with the camera bc I dont know how

    without having turned:
    upload_2023-10-4_20-54-41.png
    upload_2023-10-4_20-56-51.png

    turned around:
    upload_2023-10-4_20-55-24.png
    upload_2023-10-4_20-55-49.png
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,329
    If you're not asking a physics question then the physics forum isn't appropriate. Asking a generic scripting question is best asked on the Scripting forum so I'll move your post there for you. :)
     
    Nagonn likes this.
  3. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    421
    You have a quirky setup but drop the script below onto your AttackPoint object.

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class CamOffset : MonoBehaviour
    4. {
    5.    Vector3 offset;
    6.    void Start()
    7.    {
    8.       offset=transform.position-transform.parent.position;
    9.    }
    10.  
    11.    void Update()
    12.    {
    13.       transform.position=transform.parent.position+Camera.main.transform.rotation*offset;
    14.       transform.rotation=Camera.main.transform.rotation;
    15.    }  
    16. }
     
    faUnity and Nagonn like this.
  4. Nagonn

    Nagonn

    Joined:
    Sep 21, 2023
    Posts:
    3
    thank you
     
  5. Nagonn

    Nagonn

    Joined:
    Sep 21, 2023
    Posts:
    3
    This is perfect, thank you so much