- Home /
The code is working. Read my reply to the first comment to know why.
move camera relative to mouse position.
I want to make the camera stake to the player so i do this:
transform.position = player.transform.position + offset;
making offset to give some space between the player and the camera.
Now I want to the camera move slightly to the position of the mouse to give more vision to the player so I added this:
Vector3 mousePos = Input.mousePosition;
mousePos.z = Camera.main.nearClipPlane;
Vector3 worldPosition = Camera.main.ScreenToViewportPoint(mousePos);
worldPosition = new Vector3(worldPosition.x - 0.5f , worldPosition.y - 0.5f ,0);
worldPosition *= 2;
making the z position 0 so the player character to look at the curser in the future.
deduction 0.5 from X and Y to make the worldPosition in the centerof the screen.
but i can't add worldPosition to player.transform.position and offset becouse it will constantly add the worldPosition making the camera fly off the scene where it should be.
how do i add these variables to gather.
here is the full script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMovement : MonoBehaviour
{
[SerializeField] private GameObject player;
[SerializeField] private Vector3 offset;
private void Update()
{
Vector3 mousePos = Input.mousePosition;
mousePos.z = Camera.main.nearClipPlane;
Vector3 worldPosition = Camera.main.ScreenToViewportPoint(mousePos);
worldPosition = new Vector3(worldPosition.x - 0.5f , worldPosition.y - 0.5f ,0);
worldPosition *= 2;
Debug.Log(worldPosition);
transform.position = player.transform.position + offset + worldPosition;
}
}
and thank you for reading
"but i can't add worldPosition to player.transform.position and offset" Why would you want to add anything to the player.transform.position? I maybe missing your point but can you clarify this.
Anyway the code you posted should work just fine and nothing should "fly off"
Just make sure this script is attached to the Game Object where the Camera component is and not to the Player. If so then things certainly will "fly off"
lol! I forgot to test my code yesterday so here is what happened: yesterday I spent all of time playing and practicing unity and translating some stuff without taking any breaks form the screen or sitting so i wanted and end this script and forgot to test it after fixing some syntax problem. for wasting your time. and i am going to this post for anyone who want it because i spent all of my time researching for it. Thank you
Follow this Question
Related Questions
3D mouse position 0 Answers
Why is Input.mousePosition returning wired values using Cinemachine 2D with dynamic following? 0 Answers
Where I could find old Unity 3.5 tutorials? 0 Answers
Input.mousePosition Dead Zone - See gameplay 0 Answers
my script not working to move plane to mouse position 1 Answer