Please help with transform child rotation
I have seen and read a few similar questions in this forum, but i didn't find exactly what i was looking for.
Here is my issue:
I'm trying to make a 2D game similar to Worms. My player uses a line to help aiming which can be rotated from 0 (horizontal) to 90 degrees (vertical). When player faces to the right, it will go from 0º to 90º and when facing to the left it will go from 90º to 180º.
Since i don't understand the concept of Quaternion and how to work with it, i'm trying to do the whole thing using eulerAngles.
This is what i came up with:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControl : MonoBehaviour {
public float rotationSpeed = 25f;
public float movementSpeed = 2f;
// Use this for initialization
void Start () {
}
void Update () {
this.ControlPlayer();
this.AimControl();
}
void ControlPlayer(){
Vector3 p = transform.position;
var y = transform.eulerAngles.y;
//Prevent player from moving on the Z axis
if(p.z != 0){
p.z = 0;
}
transform.position = p;
//Player movement
var x = Input.GetAxis("Horizontal") * Time.deltaTime * movementSpeed;
//Set the direction player is facing
if(x < 0){
y = 0;
}else if(x > 0){
x = -x;
y = 180;
}
transform.eulerAngles = new Vector3(0,y,0);
transform.Translate(x, 0, 0);
}
void AimControl(){
//Child is an empty GO attached to player containing the aiming line
var child = transform.GetChild(0);
var z = Input.GetAxis("Vertical") * Time.deltaTime * rotationSpeed;
var rot = new Vector3(0,0,z);
//Limit Aim Line rotation to values between 0 and 90.
var minRot = new Vector3(0,0,0);
var maxRot = new Vector3(0,0,90);
child.Rotate(rot, Space.World);
if(child.eulerAngles.z < 0){
if(child.eulerAngles.z > -90){
child.eulerAngles = minRot;
}else{
child.eulerAngles = maxRot;
}
}else if(child.eulerAngles.z > 90){
//child.eulerAngles = maxRot;
}
}
}
My problem is in "AimControl()". I just want it not to go below 0º and above 90º regardless which side player is facing at. I've tried many modifications on the last if/else part. I've also tried to rotate it local and world but i don't really know what i'm doing and can't see any satisfying results.
Hope you guys can help me understand it better. Thanks in advance!