Zelthon
Zelthon

Reputation: 13

Affecting an object's position through another object's rotation in Unity

I have a floating gameobject (brickRot) that looks at what object is beneath it through a raycast, and then changes that object's y-position (floorY) based on brickRot's rotation. However, I'm having trouble converting rotation into a useful metric for changing Y-position. I want the current rotation of brickRot to be equal to whatever the y-position of floorY is, and then only change relative to the rotation of brickRot (if that makes any sense).

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FloorRotation : MonoBehaviour {

private float brickRot;
private float floorY;

void Update () {
    brickRot = transform.rotation.y;

    RaycastHit hit;
    Ray floorRay = new Ray(transform.position, Vector3.down);

    if(Physics.Raycast(floorRay, out hit)) {
        if(hit.collider.tag == "floor") {
            floorY = hit.transform.position.y;
            floorY = floorY + brickRot;
            Debug.Log(floorY);
        }
    }
  }
}

Think of brickRot as a plate you put down on the table, and when you rotate the plate, you change the table's y-position (if that analogy makes it any less confusing). The reason why I'm using a raycast is because there are multiple "tables" that the brick can find, and it needs to differentiate between them. If anyone has an idea of how to make this any easier, I would be forever thankful!

Upvotes: 1

Views: 1627

Answers (2)

Plexus Touristique
Plexus Touristique

Reputation: 1

use "eulerAngles" value instead , it'll convert the quaternion to an vector3 then you use angle function of vector3 to get some float, you can multiply the float with another value if you need bigger/lower scale

brickRot = angle = Vector3.Angle(transform.rotation.eulerAngles, transform.forward);

Upvotes: 0

Farhan
Farhan

Reputation: 1278

The rotation values you get are in Quaternion angles, not the common 360 degree Euler rotations. Unity, or any other game engine, uses Euler only for representation for us, but it never uses it internally for any sort of rotation calculations.

I am going to suggest not delving into deeply understanding Quaternions. But instead, think of how else you could achieve it.

For a suitable metric, add a child gameobject, rotated by 90 in x or y or z(check this, it depends on how you've oriented your parent) and some distance away from parent, to brick gameObject. Now when you rotate the brick, the child will automatically move in y, following a circular movement around the parent. You can use the child's Y as a metric for updating floorY.

Upvotes: 1

Related Questions