使转换翻译产生问题

时间:2019-02-24 01:33:05

标签: unity3d

public GameObject teleportPoint_1;
public GameObject teleportPoint_2;

void Update(){
    if (Input.GetKeyDown(KeyCode.D)) {
        transform.position = teleportPoint_1.transform.position;
        transform.rotation = teleportPoint_1.transform.rotation;

    }
        if (Input.GetKeyDown(KeyCode.A))
        {
        transform.position = teleportPoint_2.transform.position;
        transform.rotation = teleportPoint_2.transform.rotation;
    }

以下是变换值:

teleportPoint_1
位置=(0,0.3,0.67)
旋转=(-30,0,0)

teleportPoint_2
变换=(0,0.3,-0.67)
旋转=(30,0,0)

GameObject
变换=(0,2,0)
旋转=(0,0,0)

让我们解决这个问题。我已经创建了这些游戏对象,以便当您按“ A”键时,您将被传送到第一个对象(teleportPoint_1),反之亦然。

当我按下“ A”时,新的变换如下:
变换=(0,2.3,0.67)
旋转=(-30,0,0)

这不是问题,这正是我想要的
但是当我再次按下“ A”(编辑器:OP可能是“ D”)时,这是新的转换:
变换=(0,2.2248,0.06)
旋转=(0,0,0)

为什么GameObject在Z轴上滑动0.06,为什么它不返回到原始的Y坐标(2)?我尝试添加RigidBody和FreezeStats,但它们没有解决问题。

异体抗体可以帮助我吗?问题是什么,我到底要做什么?

1 个答案:

答案 0 :(得分:1)

It looks like you want to modify your transform rather than teleport to the targeted GameObject. You should increment the position and rotation of your GameObject rather than teleport to another one.

// Define the change in position and rotation
private Vector3 position_offset = new Vector3(0f, 0.3f, 0.67f);
private Vector3 rotation_offset = new Vector3(30f, 0f, 0f);

void Update()
{
    // If the 'A' key is pressed...
    if(Input.GetKeyDown(KeyCode.A))
    {
        // Increment the rotation and rotation
        transform.position += position_offset;
        transform.eulerAngles += rotation_offset;
    }
    // If the 'D' key is pressed...
    if (Input.GetKeyDown(KeyCode.D))
    {
        // Decrement the position and rotation
        transform.position -= position_offset;
        transform.eulerAngles -= rotation_offset;
    }
}

Tip: Instead of having 2 if statements, try using Input.GetAxisRaw('Horizontal') and adjusting the offset using the returned value.