Hello Guest

Author Topic: Sprite HitTest with Screen point.  (Read 5503 times)

sdragon

  • Newbie
  • *
  • Posts: 1
    • View Profile
Sprite HitTest with Screen point.
« on: August 30, 2012, 10:30:21 am »
Hello. I'm newbie game programming...

I wanna know how to hittest tk2d sprite without collider.

I have touch/mouseClick point(Input.mousePosition).

And I also have sprite/spriteDefinition data.

use sprite.getBounds() and transform position?
use spriteDefinitions.position and localScale and camerasize?

I tried many.
But I still don't know how to do it.

Please someone help me. I need any hint.

Thanks.


MooNiZZ

  • 2D Toolkit
  • Jr. Member
  • *
  • Posts: 63
    • View Profile
Re: Sprite HitTest with Screen point.
« Reply #1 on: August 30, 2012, 11:52:39 am »
Why would you want to do it without a collider? A Collider as trigger is the most optimized thing you can have in unity. You can't build a solution that's more effective than that one.

And what you want to do is convert the sprites position to screen position, because the world (0,0,0) isn't in the top left of your display, and compare the bounds of the sprite to your input position, to check if it's inside.

Else you can Just add a tk2DButton component to your sprite, for simple click behaviour.


edit: I believe The colliders use algorithms far more advanced and optimized than basic checks
Code: [Select]
if (Input.x > position.x && Input.x < position.x + bounds.x){}

« Last Edit: August 30, 2012, 11:56:30 am by MooNiZZ »

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: Sprite HitTest with Screen point.
« Reply #2 on: August 30, 2012, 01:31:47 pm »
In the event that you still want to do this the steps are:

1. Get the world space ray from the mouseposition.
Ray r = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);

2. Derive a plane from the sprite.
Plane p = new Plane(sprite.transform.forward, sprite.transform.position);

3. Check if hit and get local world position
float hitD = 0.0f;
if (p.Raycast(r, out hitD))
{
    Vector3 point = r.GetPoint(hitD);
    Vector3 localPoint = sprite.transform.worldToLocalMatrix * point;
    // do stuff here
}

4. localPoint is in the sprite local space (x -> right, y -> up). You can compare the x & y coordinates of localPoint to the bounds to see if it fits a bounding box, etc.


This will work regardless of the orientation of the sprite, camera, etc, even if they are in full 3d and not facing the camera. If the sprites will always face the camera and camera never rotates, then you can make a lot of assumptions and make things a lot simpler.