Question by
oltranzista · Jan 11, 2016 at 03:10 PM ·
rotationquaternionvector
Trouble rotating a vector point
I'm trying to rotate a vector relative to a transform.position by using Quaternion.Euler() with an angle. It works when the transform.position is (0, 0, 0), but when I change the transform.position to (0, 0, 1) I get unexpected results.
Here's my code and screens:
using UnityEngine;
using System.Collections;
public class RotateTest1 : MonoBehaviour
{
float offset = 3.5f;
void Update()
{
DrawReferenceLines();
DrawAngleLines();
}
private void DrawAngleLines()
{
// Gives expected rotation
//transform.position = new Vector3(0, 0, 0);
// Gives unexpected rotation
transform.position = new Vector3(0, 0, 1);
Vector3 pos = transform.position;
Vector3 direction = new Vector3(pos.x, pos.y, pos.z - offset);
// draw original line
Debug.DrawLine(pos, direction, Color.cyan);
float angle = 45f;
direction = Quaternion.Euler(0, angle, 0) * direction;
// draw rotated line
Debug.DrawLine(pos, direction, Color.magenta);
Debug.Log(string.Format("direction: {0}", direction));
}
private void DrawReferenceLines()
{
Vector3 pos = transform.position;
Vector3 left = pos + new Vector3(pos.x + offset, pos.y, pos.z);
Vector3 right = pos + new Vector3(pos.x - offset, pos.y, pos.z);
Vector3 front = pos + new Vector3(pos.x, pos.y, pos.z + offset);
Vector3 back = pos + new Vector3(pos.x, pos.y, pos.z - offset);
Debug.DrawLine(pos, left - pos);
Debug.DrawLine(pos, right - pos);
Debug.DrawLine(pos, front - pos);
Debug.DrawLine(pos, back - pos);
}
}
capture-good.png
(24.6 kB)
capture-bad.png
(22.5 kB)
Comment
Best Answer
Answer by oltranzista · Jan 12, 2016 at 04:16 AM
Welp, fixed my issue. I suppose it's what you're supposed to do. :)
using UnityEngine;
using System.Collections;
public class RotateTest2 : MonoBehaviour
{
float offset = 3.5f;
void Update()
{
// Get initial direction
Vector3 direction = new Vector3(0, 0, -offset);
// draw initial line
Debug.DrawLine(transform.position, transform.position + direction, Color.cyan);
// rotate the crap out of this direction :)
for (float angle = 10f; angle < 360; angle = angle + 10f)
{
// apply rotation to direction
Vector3 rotatedDirection = Quaternion.Euler(0, angle, 0) * direction;
// draw rotated line
Debug.DrawLine(transform.position, transform.position + rotatedDirection, Color.magenta);
}
}
}
capture.png
(20.5 kB)
Your answer
Follow this Question
Related Questions
Need help aiming at new world space co-ordinates for gun recoil/spray pattern 0 Answers
Help with rotating camera around object based on mouse input 0 Answers
Unity 3D C# - Rotation To Slope Of Terrain 0 Answers
Space Shooter Tutorial tilting extra 0 Answers
How to make a 2D sprite rotate towards a specific point while facing perpendicular to the camera ? 1 Answer