- Home /
Trying to make an object face the mouse, but switch sides of player based on its rotation?
So I have a 2d character that carries a tool. I want the tool to always point towards the mouse, but seeing as its being held in one hand at a time, I thought it would look best if while your mouse was on the left side of the player the tool was in the left hand and while your mouse was on the right side of the player the tool would be on the right. The way I do this currently is I have two transforms in an array as the left and right hand positions. I figured that by having a fixed point in the middle of the player that followed the mouse exactly, I would simply be able to check whether to not that objects rotation was positive (indicating left side) or negative (indicating right side) and set the tool hand position accordingly. It works fine up until you either bring your mouse directly above the player or to the bottom right of the player. In that case, the tool rapidly teleports between the two positions. I'm not sure I can wrap my head around why this problem arises. Since the tool is checking for the switch based on a fixed 360 degree point of rotation, there should be no issue, right? Any help would be appriciated.
Heres my very messy script:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class HeldTool : MonoBehaviour { public Transform[] poslist;
public Sprite[] icons;
public Transform rotateTransform;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 mousePos = UnityEngine.Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.rotation = Quaternion.LookRotation(Vector3.forward, mousePos - transform.position);
rotateTransform.rotation = Quaternion.LookRotation(Vector3.forward, mousePos - transform.position);
if (rotateTransform.rotation.z > 0){
transform.position = poslist[0].position;
} else if (rotateTransform.rotation.z < 0) {
transform.position = poslist[1].position;
} else {
transform.position = poslist[0].position;
}
Debug.Log(rotateTransform.rotation.z);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613000808im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Making an object follow the mouse in 3D world 0 Answers
Affine transformations to Object 3 Answers
Make camera 1 transform equal to camera 2 transform 1 Answer
acceleration and eulerAngle problem 0 Answers