3

Hello dear Unity game developers,

Today i have a question that seemed easy but i had a hard time solving it. In order to explain what i'm trying to achieve i made a simple illustration.

ray offset illust

I am current developing a simple mobile game which uses drag and drop system; however, as you can guess when people touch the screen the fingers usually block the view of touch position therefore i instantiate the objects with a little offset. Right now i have this simple code which works just fine achieving what i want.

 Ray ray = camera.ScreenPointToRay(Input.mousePosition)
 if(Physics.Raycast(ray, out hit, someDistance))
 {
       Instantiate(prefab, hit.point + MyOffsetVector3, Quaternion.identity)
 }

However, this system has flaws like the hit location being different than the spawn location which prevents you to do certain things like object avoidance. Therefore before i return a ray from camera's screen point which uses pixel coordinate Input.MousePosition, i want to offset it like in the illustration so i can achieve a offsetted instantiate location that is the actual hit.point from the raycast which i can check for some conditions. In simple terms, i want unity to behave like i touched higher on the screen than i have currently.

If any of you know how to offset a Pixel Coordinate which is equivalent to for example (0, 0 , 2) in world coordinates regardless of the pixel size of the phone, i might use some help.

Thanks for the help, Cheers.

2 Answers2

1

Try

    Vector3 offset = camera.transform.up * 0.1 //offset upwards by some value
    Ray ray = camera.ScreenPointToRay(Input.mousePosition)
    ray.origin += offset //add offset to ray start
    if(Physics.Raycast(ray, out hit, someDistance))
    {
       Instantiate(prefab, hit.point + MyOffsetVector3, Quaternion.identity)
    }
pacukluka
  • 728
  • 4
  • 18
0

You could offset screen point by Screen.height*0.1f (whatever number works for you). You would be offsetting by a percentage of the screen height.

Srikant
  • 26
  • 1