简体   繁体   中英

How do I find the 2D point given a start point a angle and a distance

In Unity 3D I have a GameObject with a ".transform.position" (Vector3) at some origin and I have a Vector2 position that represents a weapon position on that GameObject. In the following image the triangle is my GameObject and the green dot is the ".transform.position" of the GameObject and the red dot is the weapon position placed in front of the GameObject in this example (but it could be placed anywhere relative to the GameObject). The idea is that when a weapon fires its shot must start at the ".transform.position + weapon position" and fly off, but I am having a hard time calculating the shot start position.

在此处输入图片说明

The image shows my desired result, if the GameObject gets rotated I want my calculated weapon start position to remain in front of the GameObject. As long as my GameObject is not rotate all is fine, but when I rotate my GameObject my calculations fails and the position goes all wrong. My idea was to do something like this:

public static Vector2 GetDestinationFromPosition(Vector2 pos, float angle, float distance) {
    if(distance < 0) {
        angle = EA_Helper.GetCorrectedAngle(angle + 180.0f);
        distance = distance * -1;
    }
    float vx = Mathf.Sin(angle) * distance;
    float vy = Mathf.Cos(angle) * distance;
    return pos + new Vector2(vx, vy);
}

Vector2 shotStartPos = EA_Helper.GetDestinationFromPosition(parent.transform.position, parent.transform.eulerAngles.z + 90, positionOnShip.x);
shotStartPos = EA_Helper.GetDestinationFromPosition(shotStartPos, parent.transform.eulerAngles.z, positionOnShip.y);

But it is not working, the calculated position gets placed all around the edge of the GameObject and does not get placed where I thought it would (only if GameObject angle/rotation is zero). Can someone help me out here please?

很简单:

Vector2 shotStartPos = transform.TransformPoint(positionOnShip);

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