- Home /
How to make object face touch position
Hello I’m working on a 2D platform for phones & I can’t get my object to face the direction of a touch I’ve looked up solutions & im only getting move object to the touch position but I want the object to face the position any solutions?
You should be able to use this:
https://docs.unity3d.com/ScriptReference/Transform.LookAt.html
I don’t know if I’m doing something wrong or somethings just not working can you assist? @ShadyProductions
Those codes have multiple errors showing up on my end @Scribe
Answer by Kaskorian · May 30, 2018 at 09:17 PM
I do not know if I understood you correctly, but here is a solution to your problem as I understand it. In case of misunderstandings please correct me.
Code:
public new Camera camera;
void Update ()
{
// Check for touch
if (Input.GetMouseButton(0))
PlayerLookAtClick(Input.mousePosition);
}
private void PlayerLookAtClick(Vector3 screenTouch)
{
// calculate displacement vector (relative Position) between player position and touch position
Vector3 displacementVector = screenTouch - camera.WorldToScreenPoint(transform.position);
// make player look in that direction
transform.rotation = Quaternion.LookRotation(displacementVector);
}
You get the idea! Only problem I’m having is it’s a 2D platform but it’s rotating as if it was 3D.
Edited because I realized I got off the track ;)
public new Camera camera;
void Update ()
{
// Check for touch
if (Input.Get$$anonymous$$ouseButton(0))
PlayerLookAtClick(Input.mousePosition);
}
private void PlayerLookAtClick(Vector3 screenTouch)
{
// calculate displacement vector (relative Position) between player position and touch position
Vector3 displacementVector = screenTouch - camera.WorldToScreenPoint(transform.position);
// Since the player should not be upside down, you have to check whether you tap on the left or right side of the player and then rotate the player accordingly around its own axis
// The calculated look direction in euler angles
Vector3 preLookRotation = Quaternion.LookRotation(displacementVector).eulerAngles;
// if tap right
if (displacementVector.x > 0)
transform.rotation = Quaternion.Euler(preLookRotation.x, 90, 0);
// if tap left
else
transform.rotation = Quaternion.Euler(preLookRotation.x, -90, 0);
}
Vector3 upDirection = Vector3.up; //or whatever direction your "up" is, could even be local with "transform.up"
Quaternion.LookRotation(directiontolook, upDirection);
Your answer
Follow this Question
Related Questions
Activity Indicator Centered 0 Answers
Timer Freeze Problem 1 Answer
Character Controller with Unity User Iterface input 1 Answer
Unity Multiplayer Android Game 0 Answers
I know not how to implement the "open IAB" in unity 0 Answers