- Home /
Alternative to Camera.main.ScreenToWorldPoint
hi community :)
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!
I'm baffled by your question.
There is no reference to the character in this code, so how could it follow a character?
ScreenToWorldPoing() is used incorrectly for a perspective camera and will only return the position of the camera.
There's no code here that modifies the transform.position, so the camera will not move.
The rotation code always looks towards the world 'z'
I think you need to explain further exactly what you are trying to do, and how you have things setup.
the code above is for the rotation of the sprite. it's attached to the sprite. the camera should not rotate or do anything else. it should just follow the sprite, looking down on it, but it starts rotating as soon as i made it a child of the sprite.
Answer by froYo · Sep 03, 2014 at 11:35 AM
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.
That solved my problem! Thank you very much.
I really need to learn how to think in Unity -.-
Your answer
![](https://koobas.hobune.stream/wayback/20220613162150im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Dynamic world in Unity 4 Answers
iTween MoveAdd world coordinates Simple 2 Answers
Do I need a license when using models of real world things (cars, buildings etc)? 2 Answers
How to move Character along world floor? 2 Answers
Convert world space to GUI Rect? 5 Answers