简体   繁体   中英

AndEngine - Getting Center Coordinates of a Sprite

I have a sprite in my game and I want to get it's center coordinates. The sprite can be rotated though so I can't just get it's x/y coordinates then add half of the sprite's width/height because the getWidth and getHeight methods return the dimensions of the original, unrotated sprite.

I tried getSceneCenterCoordinates() but that for some reason returns the same coordinates for all sprites even if they are nowhere near each other.

Here's a graphic to describe what I want, the red dot is the coordinate I want, and the width/height labels on the right side figure respresent what I WANT the getWidth/Height methods to return (but they don't): 在此处输入图片说明

You can use coordinates transformer

final float[] spriteCoordinates = sprite.convertLocalToSceneCoordinates(x,y);
        final float canonX = spriteCoordinates[VERTEX_INDEX_X];
        final float canonY = spriteCoordinates[VERTEX_INDEX_Y];
Sprite sprite_in_fixedpoint_of_the_first_sprite=new Sprite(canonX,canonY,textureregion)

Get the minimum and maximum value of all the corners (for both - x and y components). Then take average from max and min to get middle:

middleX = (maxX + minX) / 2

Repeat the same for y component.

Consider something like this

    Rectangle test = new Rectangle(100, 100, 50, 100, vboManager);
    mainScene.attachChild(test);

    System.out.println("Before RotCtrX = " + test.getRotationCenterX());
    System.out.println("Before RotCtrY = " + test.getRotationCenterY());

    test.setRotation(45);
    System.out.println("After RotCtrX = " + test.getRotationCenterX());
    System.out.println("After RotCtrY = " + test.getRotationCenterY());

and the result are

System.out(4526): Before RotCtrX = 25.0
System.out(4526): Before RotCtrY = 50.0
System.out(4526): After RotCtrX = 25.0
System.out(4526): After RotCtrY = 50.0

AndEngine Entities rotate around the center (unless you change the RotationCenter values), so applying setRotate() will not affect the "center" point location

those "center" points are relative to the Entity, so if you need the actual screen coordinates, you will need to add those to the getX() and getY() values - which BTW also won't change based solely on applying a setRotate()

I figured out how to use getSceneCenterCoordinates() properly, which is to hand it a float[]. Here is my solution:

float[] objCenterPos = new float[2];
obj.sprite.getSceneCenterCoordinates(objCenterPos);
Log.d(this.toString(),  "Coordinates: ("+objCenterPos[0]+","+objCenterPos[1]+")");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM