Domanda

I am having trouble at this because frankly I never went to computer school or anything, and I think I'm sick and my brain is working at a lag haha.

So I am using Apple Sprite Kit, but the general principle is more open than that. I have one sprite that is more or less at the centre of the screen that is a bucket. Let's call this bucketSprite. Then I have another sprite, that is a hose that sprays water, and let's call this hoseSprite.

The user can drag hoseSprite around the screen with their finger. I want to change the zRotation of hoseSprite so that no matter where it is, one specific corner (the end of the hose) of it is always pointing at bucketSprite. To state it another way, the one specific corner should always be the closest point of hoseSprite in relation to bucketSprite.

How would I calculate this? I feel like if I calculate the CGPoints of bucketSprite.position, and 2 opposing corners of hoseSprite, I should be able to line them all up, but I can't think what the math would be. Thoughts?

È stato utile?

Soluzione

You can you use vector math for this problem.

You have the position of the bucket b and you have the position and direction of the hose h

             h
           .  
         . . 
    v3 .   .      
     .     . v2  
   .   .   .  
 . phi  .  .
b .........x......
      v1 

The vector v3 = v1 + v2 (vector addition). It's a directional vector.

     _____
v1 = x - b
     _____ 
v2 = h - x

The angle phi you can determine by using the dot product within the following equation:

                     __           __
             (v1 dot v3)    where v3  is the inverse of v3  
 cos(phi) =  -----------
                     __
             |v1| * |v3|    where |v1|, |v3| are the magnitudes of v1 and v3

This angle you can use to rotate your sprite in the appropriate way.

If you are in 3D space the operations are equivalent. You just have to introduce a third element to the vectors.

Altri suggerimenti

I've never used Apple Sprite Kit, but since you haven't received any answers I can take a stab at it based on the general principles of 2D sprites. What you want to do first is compute the displacement between the 2 sprites:

dx = BucketSprite.x - HoseSprite.x;
dy = BucketSprite.y - HoseSprite.y;

Then to compute the angle you'll need to do some trigonometry (arctan function, called atan usually)

HoseSprite.angle = atan(dy/dx);

If available, you'll want to use atan2(dy,dx) function instead, because it will automatically determine the proper angle from 0-360 degrees. Using just the regular atan will only work for 0-180 degrees. This is just the general idea, I'll leave the specifics and exact syntax for the implementation to you. zRotation is probably the angle in your case.

Note: Make sure the angle matches the units that are returned by the trig function, i.e. that they are both either in radians or degrees.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top