Hi. i’m a beginner developer. My question is how would I go about doing this? i’v found an script on internet and modified for my purpose.
i have a cube(player) with a rectangular cube child(gun).
on the player object i attached two script. a PlayerManager and a PlayerYRotation. the PlayerYRotation would do rotating player towards target(nearest enemy) only on y axis automatically.
on the gun obj i attached one script GunZRotation and it would do the rotating the gun only on world z axis based on user mouse position on screen.
if i disable GunZRotation, PlayerYRotation will do its job on rotating towards target on y axis. but if i enable GunZRotation, GunZRotation will do it’s jub(rotate it up and down base on mouse position) but no matter what, it’s like turret freezed on y axis. doesn’t face target on y axis.
how can i make them both to work together? maybe there should be one method for both of them, i don’t know. thanks in advance.
here is the PlayerYRotation script:
void RotationOnYAxis()
{
Vector3 direction = (target.position - transform.position).normalized;
Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * yRotationSpeed);
}
and GunZRotation Script:
void Update()
{
RotationOnZAxis();
}
void RotationOnZAxis()
{
if (Input.GetMouseButton(0))
{
Vector3 touch = Input.mousePosition;
Vector3 screen = Camera.main.ScreenToWorldPoint(new Vector3(touch.x, touch.y, Camera.main.nearClipPlane + 5.0f));
Vector3 direction = (screen - transform.position).normalized;
Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, direction.y, 0));
transform.rotation = lookRotation;
}
}