- Home /
Question by
melvincostner · Nov 19, 2021 at 11:42 AM ·
2drotationmousepositionclampz-axis
2d character, how to limit rotation to z, with character looking left?
When character is facing right the limits are from -45 to 45, and it works correctly!
When the character is facing left the limits don't work well, as from -145 to 145 is practically the full lap, I would need the limits between -145 to -180 and from 145 to 180, at least that's what I have in mind, but I can't solve
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bow : MonoBehaviour
{
PlayerController player;
PlayerInputs inputs;
PlayerAnimation animations;
public GameObject leftHand;
public GameObject rightHand;
public float min, max;
public float rotZ;
Vector3 direction;
private void Awake()
{
player = GetComponentInParent<PlayerController>();
animations = GetComponentInParent<PlayerAnimation>();
inputs = GetComponentInParent<PlayerInputs>();
}
// Update is called once per frame
void Update()
{
if (inputs.bowPressed)
{
animations.SetBow();
}
if (inputs.bowHeld)
{
BowActive();
}
else
{
leftHand.gameObject.SetActive(false);
rightHand.gameObject.SetActive(false);
}
}
void BowActive()
{
leftHand.gameObject.SetActive(true);
rightHand.gameObject.SetActive(true);
direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
direction.Normalize();
rotZ = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
if (player.direction < 0)
{
transform.localScale = new Vector3(-1, -1, 1);
rotZ = Mathf.Clamp(rotZ, min, max);
}
if (player.direction > 0)
{
transform.localScale = new Vector3(1, 1, 1);
rotZ = Mathf.Clamp(rotZ, -45, 45);
}
transform.rotation = Quaternion.Euler(0f, 0f, rotZ);
}
}
Comment
I'm having difficulty understanding what you're asking. If you need two sets of $$anonymous$$ and max values (-145, -180, 145, 180), just set two Vector2 variables instead of 2 floats.
Vector2 $$anonymous$$, max
$$anonymous$$.x = -145;
$$anonymous$$.y = -180;
max.x = 145;
max.y = 180;