- Home /
Overriding Camera.main.ScreenToWorldPoint's z value?
I'm wondering how I would go about this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CController : MonoBehaviour {
[HideInInspector]
Vector3 pos;
[HideInInspector]
float speed;
[HideInInspector]
float jumpheight;
[HideInInspector]
float gravity;
[HideInInspector]
int isjumping;
[HideInInspector]
int canjump;
[HideInInspector]
int isfalling;
void Update () {
pos = Camera.main.WorldToScreenPoint( this.transform.position);
if ( Input.GetKey(KeyCode.LeftArrow) &! Input.GetKey(KeyCode.RightArrow ))
{
pos.x -= 10.0f * Time.deltaTime;
}
if (Input.GetKey(KeyCode.RightArrow) & !Input.GetKey(KeyCode.LeftArrow))
{
pos.x += 10.0f * Time.deltaTime;
}
pos.z = 0;
this.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(pos.x, pos.y, pos.z));
}
}
The above script is attached to my player sprite. When I run the game in the editor the player is invisible because it adopts the same -10 value as the camera. Even though I put pos.z = 0 the conversion back to World co-ords still reverts back to -10 for the z value.
How do I override this or is there a better way using layers to make my sprite visible?
Comment
Best Answer
Answer by avvie · Apr 12, 2018 at 10:07 AM
I am not sure what this script is trying to accomplish exactly to provide more insightful information. ANyway I did fix your problem, but i did not make any attempt to optimize it
void Update () {
pos = Camera.main.WorldToScreenPoint( this.transform.position);
if ( Input.GetKey(KeyCode.LeftArrow) &&! Input.GetKey(KeyCode.RightArrow ))
{
pos.x -= 10.0f * Time.deltaTime;
}
if (Input.GetKey(KeyCode.RightArrow) && !Input.GetKey(KeyCode.LeftArrow))
{
pos.x += 10.0f * Time.deltaTime;
}
Vector3 temp = Camera.main.ScreenToWorldPoint(new Vector3(pos.x, pos.y, pos.z));
pos = temp;
pos.z = 0;
this.transform.position = pos;
}