- Home /
Problem with Parent and Child using LookAt
I am making a 2D platformer gunner. The gun aims at the mouse position. I have an invisible 'arm' which acts as a pivot point and the parent of the 'gun' and the 'barrel'. Everything works fine except...
I need the barrel to stay at 0 because that is where the bullets get instantiated from. The barrel stays in place when aiming to the right of my character, but when aiming to the left the barrel.transform.postion.z goes from 0 to -1.5.
Also in the inspector it shows the arms y rotation just jumping back and forth between 90° and 270°.
using UnityEngine;
using System.Collections;
public class GunContLookAt : MonoBehaviour {
public GameObject barrel;
public GameObject arm;
public Vector3 pubMousePos;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 mousePos2 = new Vector3(mousePos.x,mousePos.y, arm.transform.position.z);
pubMousePos = mousePos2;
arm.transform.LookAt(mousePos2);
// Test doesnt work
while (mousePos2.y > 90)
{
barrel.transform.position = new Vector3(barrel.transform.position.x, barrel.transform.position.y, 0f);
}
}
}
Hi there. First thing to notice: Don't use while(){} because it runs everything {/here/} in one frame. That mean in your case it just freezes your computer.
If you are trying to lock the position using while loop,try If condition ins$$anonymous$$d of while loop
//Test doesn't work
if(mousePos2.y > 90)
{
barrel.transform.position = new Vector3(barrel.transform.position.x, barrel.transform.position.y, 0f);
}
If the barrel has a rigid body, you can select the constraint to freeze the Z axis for transform and/or rotation. If this is not the case, @sethuraj has provided a good option above to hold the barrel in place through code.
I tried the if statement, it didnt work which is why I tried a while loop which didnt work.
I have also tried restricting the rotation of z and y on all components of the gun and it doesnt do anything, lookAt overrides it.
Your answer
Follow this Question
Related Questions
Make a simple tree 1 Answer
Zooming camera to child objects of .obj model 0 Answers
How do I get the global position 2 Answers
Behave like another object is parent? 2 Answers
How can I make a game object follow an instantiated game object? 1 Answer