- Home /
Move relative to screen
I use top down 60 degree tilted camera and want move always visually straight directions relative to screen (up, down, left, right). When object is near screen edges it starts moving diagonally (visually) probably because of camera tilt.
I tried with WorldToViewportPoint
/ ViewportPointToRay
but it doesnt work exactly because even when there is no input, conversion to viewport and back to world same value sometimes gives slighltly offset from start position.
float delta = Time.deltaTime;
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
Vector3 view = MainCamera.WorldToViewportPoint(transform.position);
view.x = (h > 0) ? 1 : (h < 0) ? 0 : view.x;
view.y = (v > 0) ? 1 : (v < 0) ? 0 : view.y;
Ray ray = MainCamera.ViewportPointToRay(view);
RaycastHit hit;
Physics.Raycast(ray, out hit, Mathf.Infinity, 1 << 15); // 15 - ground plane layer
Vector3 world = new Vector3(hit.point.x, transform.position.y, hit.point.z);
Vector3 dir = (world - transform.position).normalized;
transform.position += dir * Speed * delta;
Comment
Your answer
Follow this Question
Related Questions
Moving player in direciton camera is facing 1 Answer
How to synchronize both movement and rotation? 1 Answer
Camera Movement and angles 2 Answers
UNITY 3D: How to make the camera follow the player? Smoothly 2 Answers
3D RTS camera 3 Answers