I have a GameObject called Gun, and a GameObject called Hand which is a child of other GameObject named Player.
When I pick up the gun, it becomes a child of the hand.
The problem is, when the player rotates (and so, Hand rotates too), the gun's not rotating, it stays at the same rotation.
Here's the Gun script:
using System.Collections.Generic;
using UnityEngine;
public class LaserGun : MonoBehaviour
{
public GameObject Hand;
public Transform LaserSpawnPoint;
public Movement movement;
public Rigidbody2D rb2D;
public GameObject Laser;
public bool IsInHand;
public void Start()
{
Hand = GameObject.Find("Hand");
movement = GameObject.Find("Player").GetComponent<Movement>();
rb2D = this.GetComponent<Rigidbody2D>();
}
public void OnMouseDown()
{
this.transform.parent = GameObject.Find("Hand").transform;
this.transform.position = Hand.transform.position;
GetComponent<BoxCollider2D>().isTrigger = true;
GetComponent<Rigidbody2D>().isKinematic = true;
IsInHand = true;
}
public void Update()
{
if (Input.GetKeyDown(KeyCode.E) && IsInHand == true)
{
Instantiate(Laser, LaserSpawnPoint.position, transform.rotation);
}
if (Input.GetKeyDown(KeyCode.Q) && IsInHand == true)
{
this.transform.parent = null;
GetComponent<BoxCollider2D>().isTrigger = false;
GetComponent<Rigidbody2D>().isKinematic = false;
IsInHand = false;
}
}
}
And here's the Player's movement script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float speed;
public float jumpForce;
public float moveInput;
public GameObject Hand;
public GameObject HeldObj;
private Rigidbody2D rb;
public bool facingRight = true;
private bool isGrounded;
public Transform groundCheck;
public float checkRadius;
public LayerMask whatIsGround;
void Start()
{
rb = GetComponent<Rigidbody2D>();
Hand.transform.rotation = this.transform.rotation;
}
void FixedUpdate()
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);
moveInput = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
if (facingRight == false && moveInput > 0)
{
Flip();
Hand.transform.Rotate(new Vector3(0, -180, 0));
}
else if (facingRight == true && moveInput < 0)
{
Flip();
Hand.transform.Rotate(new Vector3(0, 180, 0));
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true)
{
rb.velocity = Vector2.up * jumpForce;
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
}
Some info (might be useful)
- The game is 2D
- The "Hand" object is an empty game object
- There is no animator on player and the gun objects
I tried to upload the image of this but for some reason Stack does not let me do this.
Any help will be appreciated!