最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Transform.InverseTransformPoint Unexpected Return Values in Unity 6 - Stack Overflow

programmeradmin1浏览0评论

I am working on a game for a game jam. I'm working in unity2D version 6000.0.32f1. I am attempting to get a circle which is my enemy to face my player which is also a circle by updating the enemy circle's rotation each frame to face the player's circle position. I am using code that I built which causes the player circle to follow the mouse position by calculating the angle between the x and y displacements of the pointer location in world coordinates. I am attempting to use Transform.InverseTransformPoint to calculate the local position of the player circle in relation to the enemy circle. The return value of the function fluctuates between what I'd expect which is the player circle's position relative to the enemy circle and a value that I did not expect which is zero on the x axis and close to the previously mentioned position in this sentence's value on the x axis on the y-axis.

I used the following code. As mentioned above I got return values from the transform.InverseTransformPoint(playerPos) function call that were unexpected every other call to the function. See picture below of output.

using System;
using UnityEngine;

public class Enemy : MonoBehaviour {
    Player player;

    void Start () {
        player = FindFirstObjectByType<Player>();
    }

    void Update () {
        EnemyAI();
    }

    void EnemyAI () {
        if (player == null) return;
        Vector3 playerPos = player.gameObject.transform.position;
        
        // Look at Player
        Debug.Log("Enemy Player Position: " + playerPos);
        Vector3 playerPosRel = transform.InverseTransformPoint(playerPos);
        Debug.Log("Enemy Player Position Relative: " + playerPosRel);
        float rotationAngle = playerPosRel.x < Mathf.Epsilon ? 0 :
        Mathf.Atan(playerPosRel.y/playerPosRel.x) * Mathf.Rad2Deg;
        Debug.Log("Enemy Rotation Degrees: " + rotationAngle);
        
       
        transform.rotation = Quaternion.Euler(
            0,
            0,
            Mathf.Sign(playerPosRel.x) < 0 ?
            90 + rotationAngle : 
            -90 + rotationAngle
        );
        
        
        // Approach Player
        transform.position = Vector3.Lerp(
            transform.position, 
            playerPos, 
            Time.deltaTime
        );
    }
}

The output of my code which returns an unexpected value every other call to InverseTransformPoint Why is InverseTransformPoint returning these unexpected values? How does InverseTransformPoint work? What operation could I try separately independent of InverseTransformPoint to get the player position relative to the enemy?

发布评论

评论列表(0)

  1. 暂无评论