user10998008
user10998008

Reputation:

Making transform translate create problem

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;
    }

Here are the transform values:

teleportPoint_1
Position = (0, 0.3 , 0.67)
Rotation = (-30, 0, 0)

teleportPoint_2
Transform = (0, 0.3 , -0.67)
Rotation = (30, 0, 0)

GameObject
Transform = (0, 2 , 0)
Rotation = (0, 0, 0)

Let's get to the problem. I have created these Game Objects so that when you press 'A' you get teleported to the first object (teleportPoint_1) and vice-versa for 'D'.

When I press 'A' once the new transform is as follows:
Transform = (0, 2.3 , 0.67)
Rotation = (-30, 0, 0)

This is not a problem, this is exactly what I want
But then when I press 'A' (editor: OP probably meant 'D') once again and here is the new transform:
Transform = (0, 2.2248 , 0.06)
Rotation = (0, 0, 0)

Why is the GameObject gliding by 0.06 on the Z-axis and why does it not return to the original Y coordinate (2)? I have tried adding a RigidBody and FreezeStats but they didn't solve the problem.

Can anobody help me? What is the problem and what is it exactly that I have to do?

Upvotes: 0

Views: 35

Answers (1)

Savaria
Savaria

Reputation: 565

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.

Upvotes: 1

Related Questions