Reputation: 1180
The first thing you will notice is the complicated and confusing title. So let me explain that.
I'm trying to make an 2D game in an 3D space using Unity. And i'm using a 3D Character as an Player. This looks like that :
As you can see the Background ( A Google map ) is two dimensional. While the Player is a 3D Object laying on the ground ( It just Looks like it is Standing ).
Thats working fine so far. But i want that the 3D Character Looks like it is facing a tapped Point on the Background map.
For example :
And two more examples :
The black circle represents the tapped Position. So i have totally no clue if theres a way to do that, or even if its possible to do that.
I tried the following code, but that only rotates my character on an different axis :
Vector3 targetDir = tapped.position - transform.position;
float step = speed * Time.deltaTime;
Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0F);
transform.rotation = Quaternion.LookRotation(newDir);
Is there even a way to achieve that ? Im currently out of ideas... I would be very glad for any help i can get !
Upvotes: 1
Views: 593
Reputation: 967
This should do the trick. Make your model a child of an unrotated empty, facing is like in your first image, and put the below script on it. I didnt know how you get the point to look at, it is what i tried in unity. Hope it helps.
using UnityEngine;
public class LookAtTarget : MonoBehaviour {
//assign in inspector
public Collider floor;
//make sure you Camera is taged as MainCamera, or make it public and assign in inspector
Camera mainCamera;
RaycastHit rayHit;
//not needed when assigned in the inspector
void Start() {
mainCamera = Camera.main;
}
void Update () {
if(Input.GetMouseButtonUp(0)) {
if(floor.Raycast(mainCamera.ScreenPointToRay(Input.mousePosition), out rayHit, Mathf.Infinity)) {
//its actually the inverse of the lookDirection, but thats is because the rotation around z later.
Vector3 lookDirection = transform.position - rayHit.point;
float angle = Vector3.Angle(lookDirection, transform.forward);
transform.rotation = Quaternion.AngleAxis(Vector3.Dot(Vector3.right, lookDirection) > 0 ? angle : angle * -1, Vector3.forward);
}
}
}
}
Upvotes: 1