- Home /
Camera.main.WorldToScreenPoint(touch.position). Help !!!
Hi guys! I'm newbie. I am acquainted with Unity and I have the code:
public GameObject player01;
public GameObject player02;
public float jumpHeight;
void Update () {
if(Application.platform == RuntimePlatform.Android){
if(Input.touchCount > 0) {
for (int i = 0; i < Input.touchCount; ++i) {
Touch touch = Input.GetTouch(i);
if (touch.phase == TouchPhase.Began) {
float y = Camera.main.WorldToScreenPoint(touch.position).y;
if (y <= Screen.height/2f) {
player01.rigidbody2D.AddForce(Vector2.up * jumpHeight);
} else if (y > Screen.height/2f) {
player02.rigidbody2D.AddForce(Vector2.up * jumpHeight);
}
}
}
}
}
}
Current code does not work as expected. Please help! Thanks!
Image:
Answer by hbalint1 · May 01, 2015 at 09:41 PM
The quick solution:
change this:
float y = Camera.main.WorldToScreenPoint(touch.position).y;
to this:
float y = touch.position.y;
The longer explanation:
First of all you don't need to convert the touch position to anything. the touch.position gives back the coordinates of your touch. you just need the y coordinate so touch.position.y is what you are looking for. If anytime you will need the world position for your touch (like you want to shoot there or something) you need to use ScreenToWorldPoint() not the WorldToScreenPoint(). I didn't meet any situation where I had to use WorldToScreenPoint(). It takes the 3D world position of an object and projects it to the 2D screen. (if it was a mispelling, i'm sorry)