Alternative to Camera.main.ScreenToWorldPoint

hi community :slight_smile:

i’m absolutely new to Unity3d and c# as well.

currently i’m trying to create a little top down view game and run into one big issue, which i cannot solve by myself.

first i tried to move around a character (sprite) with WASD. succeeded.

then i added some kind of a “look at mouse” script. that’s working, too.

now, i want my camera to follow the character. fails!

i thought, i could easily make the mainCamera as a child of the sprite in the hierachy, but that causes my sprite to rotate around its z-axis constantly.

my guess is, that this results from the way, how i calculate the new rotation of the sprite.

using UnityEngine;
using System.Collections;

public class LookAtMouse : MonoBehaviour {

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
		
		transform.rotation = Quaternion.LookRotation(Vector3.forward, mousePos - transform.position);
		Debug.Log ( Input.mousePosition + " vs " + mousePos);
	}
}

yes, that’s where i’m stuck now.
i think, there’s a way to solve it, if i could only figure out how.
maybe you could calculate the mousepointer’s position (in the world) using another way?

Thanks!

Create a new script and add this.

public Transform playerTransform;

	void Update ()
	{
		transform.position = new Vector3(playerTransform.position.x, playerTransform.y, transform.position.z);
	}

Drag this script onto your camera and drag the player into the playerTransform variable in the editor.

For smoother movement, consider using:

Vector3.Lerp

Hope this helps.