Questions in topic: "quaternion"
http://answers.unity.com/questions/topics/single/346.html
The latest questions for the topic "quaternion"Rotate Gameobject by vertex shader with quaternion
http://answers.unity.com/questions/1737765/rotate-gameobject-by-vertex-shader-with-quaternion.html
Hi, I am trying to rotate a cube by vertex shader with quaternion, the cube position is (0,0,1), and rotate axis is (1,0,0), I had tried the quaternion rotate method, but things do not work like I expected, it scale up and down the gameobject from the (0,0,0) point, what did I do wrong, this is driving me crazy since I can not figure out why. Please help! Here is my whole shader code :
Shader "Unlit/NewTestTrackShader"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_OffsetX("Offset X",float) = 0
_OffsetY("Offset Y",float) = 0
}
SubShader
{
Tags { "RenderType"="Opaque" "Queue"="Transparent-1"}
LOD 100
Blend SrcAlpha OneMinusSrcAlpha
Pass
{
Cull Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
float4 posWorld : TEXCOORD1;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
float4 posWorld : TEXCOORD1;
};
float4 RotateionAxisToQuaternion(float3 axis,half angle){
half half_angle = radians(angle/2);
float4 q = (axis.x * sin(half_angle),
axis.y * sin(half_angle),
axis.z * sin(half_angle),
cos(half_angle));
return q;
}
/////////
float3 RotateVertexposition(float3 vertexPosition,float3 axis,float angle){
float4 q = RotateionAxisToQuaternion(axis,angle);
float3 v = vertexPosition;
return v + 2 * cross(q.xyz,cross(q.xyz,v) + q.w * v);
}
//// Equal Above Function
float4 quat_mult(float4 q1, float4 q2){
float4 qr;
qr.x = (q1.w * q2.x) + (q1.x * q2.w) + (q1.y * q2.z) - (q1.z * q2.y);
qr.y = (q1.w * q2.y) - (q1.x * q2.z) + (q1.y * q2.w) + (q1.z * q2.x);
qr.z = (q1.w * q2.z) + (q1.x * q2.y) - (q1.y * q2.x) + (q1.z * q2.w);
qr.w = (q1.w * q2.w) - (q1.x * q2.x) - (q1.y * q2.y) - (q1.z * q2.z);
return qr;
}
float4 quat_conj(float4 q){
return float4(-q.x, -q.y, -q.z, q.w);
}
float3 rotate_vertex_position_detail(float3 position, float3 axis, float angle){
float4 qr = RotateionAxisToQuaternion(axis, angle);
float4 qr_conj = quat_conj(qr);
float4 q_pos = float4(position.x, position.y, position.z, 0);
float4 q_p = quat_mult(qr, q_pos);
float4 qp_q = quat_mult(q_p, qr_conj);
return float3(qp_q.x, qp_q.y, qp_q.z);
}
////////////////////
sampler2D _MainTex;
float4 _MainTex_ST;
float_OffsetX,_OffsetY,;
v2f vert (appdata v)
{
v2f o;
o.posWorld = mul(unity_ObjectToWorld, v.vertex);
float3 axis_X = (1,0,0);
float3 axis_Y = (0,1,0);
float3 axis_Z = (0,0,1);
o.posWorld.xyz = rotate_vertex_position_detail(o.posWorld.xyz, axis_X, _OffsetX);
v.vertex = mul(unity_WorldToObject, o.posWorld);
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);
return half4(col);
}
ENDCG
}
}
}
and here is what it look like :
![alt text][1]
[1]: /storage/temp/161050-screen-shot-2020-06-03-at-24105-pm.pngshaderquaternionrotateThu, 04 Jun 2020 15:36:56 GMTHan-Wenhow do i use Quaternion lerp on only the Y and Z axis
http://answers.unity.com/questions/1738126/how-do-i-use-quaternion-lerp-on-only-the-y-and-z-a.html
https://streamable.com/6v34kh
im trying to make it so that my car slowly rotates towards 0,0,0 except the X axis, in the video i almost have that except for some reason the x rotation starts to freeze.
here is my entire script:
https://pastebin.com/t0xufY0c
but this is the line of code that mainly has to do with the issues:
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(transform.eulerAngles.x, 0, 0), Time.deltaTime);rotationquaternionlerpThu, 04 Jun 2020 05:08:44 GMTGlowball123Add force to player at a certain z angle in 2D
http://answers.unity.com/questions/1737949/add-force-to-player-at-a-certain-z-angle-in-2d.html
Hello, I want to add a force at a certain z angle(which is a moving arrow going in a circle). I have accessed the rotation of that arrow by using
<code>arrow.transform.rotation.eulerAngles.z</code>
So now how do I add a force on the player at the above z rotation? Thanks a lot in advance!! ^_^
Note: This whole project is in 2D2drotationquaterniontrajectoryarrowWed, 03 Jun 2020 17:16:23 GMTAryanJumaniRotate vector towards another vector around perpendicular vector
http://answers.unity.com/questions/1737735/rotate-vector-towards-another-vector-around-perpen.html
Given three vectors in 3D Space *V0*, *V1* and *V2*, where *V1* is perpendicular to *V0*. How could I rotate *V0* around *V1*'s axis so that it points in the direction of *V2*?
In other words, rotate *V0* around *V1* so that the projection vector *Vp* between *V0* and *V2* is of minimum magnitude.
Figure 1 is the starting point, and Figure 2 is the result I want.
![alt text][1]
[1]: /storage/temp/161048-vectors.pngrotationvector3quaternionmagnitudeWed, 03 Jun 2020 02:16:50 GMTFede192How to finish a Quaternion.Euler rotation when you let go of the input?
http://answers.unity.com/questions/1736620/how-to-finish-a-quaternioneuler-rotation-when-you.html
I am trying to make my character flip like in Paper Mario. When I let go of the input key, the lerping stops, so basically my question is how to "finish" lerping when a key is let go of. This is my flipping/moving code.
void Start()
{
playerRb = this.GetComponent<Rigidbody2D>();
playerTr = this.GetComponent<Transform>();
}
void FixedUpdate()
{
playerRb.velocity = new Vector2(Mathf.Lerp(0, Input.GetAxis("Horizontal") * moveSpeed, 0.4f), Mathf.Lerp(0, Input.GetAxis("Vertical") * moveSpeed, 0.4f));
if (Input.GetKey(KeyCode.D) && playerTr.rotation.y != 0)
{
PlayerRotator(0);
}
if (Input.GetKey(KeyCode.A) && playerTr.rotation.y != 180)
{
PlayerRotator(180);
}
}
void PlayerRotator(int angle)
{
playerTr.rotation = Quaternion.Lerp(playerTr.rotation, Quaternion.Euler(transform.rotation.x, angle, transform.rotation.z), rotSpeed);
}gamequaternionmovement scriptgamesTue, 02 Jun 2020 15:02:34 GMTWhaleLukeRotate rect transform ui by touch
http://answers.unity.com/questions/1737555/rotate-rect-transform-ui-by-touch.html
I have an ui rect transform with image. I want to rotate it rect transform z axis based on swipe on screen (on x and y axis screen) infront of it rect transform only. So if the player swiping in other area outside the rec transform won't do anything. How to achieve that?rotationuimobilequaternionrecttransformTue, 02 Jun 2020 13:25:35 GMTTri-gonalRotation to align between two vectors but with preserved Camera Z axis
http://answers.unity.com/questions/1736324/rotation-to-align-between-two-vectors-but-with-pre.html
Vector3 firstPoint = _waypoints.First();
Vector3 lastPoint = _waypoints.Last();
Vector3 relativePos = lastPoint - firstPoint;
Vector3 middlePoint = Vector3.Lerp(firstPoint, lastPoint, 0.5f);
Instantiate(prefab, firstPoint, Quaternion.identity);
Instantiate(prefab, lastPoint, Quaternion.identity);
GameObject slash = Instantiate(slashPrefab, middlePoint, player.rotation);
slash.transform.rotation = Quaternion.FromToRotation(Vector3.right, relativePos);
Given slash prefab (white mark on screenshot) I want it to point always in the direction I'm looking (player z-axis) but be rotated so it's pointing from cube to cube as the purple lines.
How can I combine player.rotation/forward with the Quaternion.FromToRotation(Vector3.right, relativePos)
----------
![alt text][1]
[1]: /storage/temp/160716-inkedinkedunity-rw9adtduxi-li2.jpgunity 5rotationvector3quaternionaxisFri, 29 May 2020 22:32:53 GMTstychuvery specific question about rotating children opposite to rotation of parent using quaternions (or something like that)
http://answers.unity.com/questions/1733814/very-specific-question-about-rotating-children-opp.html
ill have the script i use at the end of this, but its a spaghetti fest (seriously, its a nightmare down there you don't have to help if you don't want to). so ill simplify what i have so far; a main rigidbody which is using quaternion.slerp to rotate to the direction of the normal directly below it using a raycast (i don't know how this works exactly but i multiply a part of it by the rigidbody's rotation and another quaternion for rotation around the y axis and it just works) the rigidbody doesn't have gravity and has a constant local force applied to its y axis. also there's a camera as a child of the main rigidbody which only gets the x axis modified using quaternion.euler, in short that makes it work like a regular fps player sorta thing. what i want to do now is get the x rotation of the camera to not be effected by the rotation of the main rigidbody so it can look at something else while the main rigidbody changes its rotation. is this even possible? any advice?
#region
float xRot = Input.GetAxisRaw("Mouse X");
float yRot = Input.GetAxisRaw ("Mouse Y");
Vector3 rbRot = new Vector3(0f, xRot, 0f) * camsensitivity;
Vector3 camRot = new Vector3((-yRot * 1.6f), 0f, 0f) * camsensitivity;
//Debug.Log (camera.rotation);
if (camera.localEulerAngles.x > 270f){
//camera.rotation = Quaternion.Euler(90f, 0f, 0f);
//Debug.Log("euler is greater than 270");
}
if (camera.localEulerAngles.x > 80f && camera.localEulerAngles.x < 300f){
//camera.rotation = Quaternion.Euler(90f, 0f, 0f);
//Debug.Log("euler is less than 90");
}
//Debug.Log(manualangle);
//rotate towards normal
RaycastHit normalchek;
Physics.Raycast (transform.position, transform.TransformDirection(Vector3.down), out normalchek);
//transform.rotation = Quaternion.FromToRotation(transform.up, normalchek.normal) * transform.rotation;
if (normalchek.distance < 3f && normalchek.transform.gameObject.tag == "grappleable") {
cantmove = false;
//camera.localRotation = (camera.localRotation * Quaternion.Euler(camRot) * Quaternion.Inverse(Quaternion.FromToRotation (transform.up, normalchek.normal)));
//camera.localRotation = (camera.localRotation * Quaternion.Euler(camRot));
//transform.rotation = Quaternion.FromToRotation (transform.up, normalchek.normal) * transform.rotation * Quaternion.Euler (rbRot);
//player.MoveRotation(player.rotation * Quaternion.Euler (rbRot));
transform.rotation = Quaternion.Slerp(player.rotation * Quaternion.Euler (rbRot), Quaternion.FromToRotation (transform.up, normalchek.normal) * transform.rotation * Quaternion.Euler (rbRot), 0.4f);
} else {
player.MoveRotation(player.rotation * Quaternion.Euler (rbRot));
//camera.Rotate (camRot);
}
//wanna rotate to where youre looking at?
RaycastHit normalchek1;
Physics.Raycast (camera.position, camera.transform.forward, out normalchek1);
//Debug.Log(normalchek1.distance);
if (Input.GetKeyDown(KeyCode.Mouse1) && !grounded && normalchek1.transform.gameObject.tag == "grappleable"){
if (normalchek1.distance < grappledist) {
cantmove = true;
player.velocity = new Vector3 (0f, 0f, 0f);
transform.rotation = Quaternion.FromToRotation (transform.up, -(normalchek1.point - camera.transform.position)) * transform.rotation;
if (Random.Range (-1f, 1f) > 0f) {
Instantiate (shock1, transform.position, transform.rotation);
} else {
Instantiate (shock2, transform.position, transform.rotation);
}
} else {
Instantiate (shockfail, transform.position, transform.rotation);
}
}
//moves the camera
camera.Rotate (camRot);
//the float with the "fake" angle
manualangle += camRot.x;
//Debug.Log(camera.localEulerAngles);
if (manualangle > 90f){
camera.localEulerAngles = new Vector3 (90f, 0f, 0f);
manualangle = 90f;
}
if (manualangle < -90f){
camera.localEulerAngles = new Vector3(-90f, 0f, 0f);
manualangle = -90f;
}
#endregionquaternionTue, 26 May 2020 16:12:01 GMTuni-TTSlerp Finishes Rotation When Progress is 0.5f
http://answers.unity.com/questions/1734510/slerp-finishes-rotation-when-progree-is-05f.html
Hi,
I have a question about using Slerp method. I'm using it to rotate an object so that it will be looking at a point. However as far as I know, when progress is 1, Slerp will be done. But in my case it turns towards the point I want when progress is 0.5f. And If I continue turning until progress is 1, it turns back to its original rotation.
Actually my code is working in that way but I wonder why it doesn't work as it should when slerp is called until progress is 1. Thanks in advance!
private IEnumerator TurnTowardsFinalTrack_CO()
{
float progress = 0f;
Transform centerP = selectedRunway.GetRunwayCenterPoint();
Vector3 dirVector = -centerP.position + transform.position;
Quaternion targetRotation = Quaternion.LookRotation(dirVector, Vector3.forward);
Vector3 correctionVector = Vector3.zero;
while (progress < 0.5f) //weirdly works in that way
{
transform.transform.rotation = Quaternion.Slerp(transform.transform.rotation, targetRotation, progress);
correctionVector.z = transform.transform.eulerAngles.z;
transform.eulerAngles = correctionVector;
progress += Time.deltaTime;
yield return null;
}
}rotationquaternioncoroutineslerpprogressMon, 25 May 2020 12:50:28 GMTHectorOfPriamosGame Object rotation sometimes doesn't match defined quaternion
http://answers.unity.com/questions/1733842/game-object-rotation-sometimes-doesnt-match-define.html
I'm trying to set a ship to rotate to match a curved ramp and also to face forward as it moves around the ramp. I have a solution which I believe should work but at specific points on the ramp the ship rotation changes to completely different (but consistent) rotations.
The rotation is defined as below:
RaycastHit hit;
Physics.Raycast(transform.position, -(transform.up), out hit);
Vector3 forwardDir = Vector3.Cross(transform.right, hit.normal);
Debug.DrawRay(transform.position, forwardDir, Color.blue);
Debug.DrawRay(transform.position, hit.normal, Color.red);
Quaternion newLook = Quaternion.LookRotation(forwardDir, hit.normal);
transform.rotation = Quaternion.Slerp(transform.rotation, newLook, 0.05f);
Does anyone have any idea why the ship might rotate like this sometimes:![alt text][1]
[1]: /storage/temp/160179-screenshot-3-min.pngrotationphysicsvector3quaternionSat, 23 May 2020 11:16:28 GMTme136703Pendulum (harmonic motion) should start at center
http://answers.unity.com/questions/1733277/pendulum-harmonic-motion-should-start-at-center.html
I'm trying to create a harmonic motion effect for a spotlight to let it swing back and forth on its local Y axis.
This generally works fine, but I want the motion to actually start from the center between "_left" and "_right" instead of starting at either of the extremes. Can this be accomplished?
public float rotationSpeed = 1.0f;
public float maxRotation = 35f;
Quaternion _left, _right;
float turnTime;
void Start () {
turnTime = 0.0f;
_left = Quaternion.AngleAxis (maxRotation, Vector3.up);
_right = Quaternion.AngleAxis (-maxRotation, Vector3.up);
}
void Update () {
turnTime += Time.deltaTime;
transform.localRotation = Quaternion.Lerp (_left, _right, (Mathf.Sin (turnTime * rotationSpeed + Mathf.PI / 2) + 1.0f) / 2.0f);
}
Please ask me to elaborate if in doubt about what I mean, and I will try my best.
Thanks in advance.quaternionFri, 22 May 2020 08:38:53 GMTwormple12Random.insideUnitCircle seems to reproduce similar vectors
http://answers.unity.com/questions/1733266/randominsideunitcircle-seems-to-reproduce-similar.html
I am using Random.insideUnitCircle to calculate a random vector in which for my enemy to look when searching for the player. The enemy will stare in this direction for a few seconds, then a new vector will be calculated and he will turn his head.
These are the variables I set whenever the new vector needs to be calculated:
`
endRot = Random.insideUnitCircle.normalized;
step = lookSpeed * Time.deltaTime;`
Here is my Update():
`
transform.rotation = Quaternion.LookRotation(Vector3.RotateTowards(transform.forward, endRot - (Vector2)transform.position, step, 0f));
Debug.DrawRay(transform.position, endRot - (Vector2)transform.position, Color.red);`
The issue is that the vectors are all extremely close to each other and so the enemy doesn't seem to be looking around. The Debug.DrawRay() confirms that the directions are within a few degrees of each other, even if I recalculate the vectors multiple times and have the enemy look around a lot.
I have also tried changing the Random.InitState() before using Random.insideUnitCircle. If I need to post all the code let me know.rotationvector3quaternionrandomThu, 21 May 2020 14:16:54 GMTlogane616Quaternion.FromToRotation() 3D direction on 2 axes.
http://answers.unity.com/questions/1732653/quaternionfromtorotation-3d-direction-on-2-axes.html
Hello. I play around with procedural generating rooms.
I created an small room with two entries. On every entry i put two helper objects wich hold the positon and direction. On every entry i want to connect other rooms.
This helper object are for:
1. The Postion of the entry
2. Wich directon is the entry.
With this two points, i can calculate the offset of the next room. So that it fit exactly to the existing entry.
For this calculation i need to turn the the offset to the direction of the door.
The Calculation -> get the offset from an not instanciated prefab (it is based on quaternion.identity) --> Turn this offset in direction of the door.
**With this code i get the direction of the door.**
Vector3 visitDirection = helper1.position- helper2.position;
Quaternion visitRotation = Quaternion.FromToRotation(Vector3.left,visitDirection.normalized);
**With this code do i turn the offset vector.**
Vector3 turnedDirection = visitRotation * modelOffset;
When the direction of the base element is just turned on one axis from zero. Example for understanding, like Euler(0.0,33.0,0.0) or Euler(0.0,0.0,-100.0). Then it works fine and FromToRotation give me the right direction and the calculation will succsess.
**Now the issue:**
If the orientation of the base element is turned on 2 axes, also when i turn it in inspector. Like(0.0,12.5,43.3) In this case the Function Quaternion.FromToRotation() calculate the wrong direction. The code below proves it.
Vector3 turn_Y_Axe = new Vector3(-0.7f,0.0f,0.7f); // -> Euler(0.0f,45.0f,0.0f)
Vector3 turn_Z_Axe = new Vector3(-0.7f,-0.7f,0.0f); // -> Euler(0.0f,0.0f,45.0f)
Vector3 turn_YZ_Axe = new Vector3(-0.5f, -0.7f, 0.5f); // -> Euler(0.0f,45.0f,45.0f)
Quaternion rotation_Y_Axe = Quaternion.FromToRotation(Vector3.left,turn_Y_Axe);
Quaternion rotation_Z_Axe = Quaternion.FromToRotation(Vector3.left,turn_Z_Axe);
Quaternion rotation_YZ_Axe = Quaternion.FromToRotation(Vector3.left,turn_YZ_Axe);
Debug.Log("Y Axe: " + rotation_Y_Axe.eulerAngles.ToString());
Debug.Log("Z Axe: " + rotation_Z_Axe.eulerAngles.ToString());
Debug.Log("YZ Axe: " + rotation_YZ_Axe.eulerAngles.ToString());
/* Output log ************************************************
Y Axe: (0.0, 45.0, 0.0)
UnityEngine.Debug:Log(Object)
Z Axe: (0.0, 0.0, 45.0)
UnityEngine.Debug:Log(Object)
YZ Axe: (346.4, 31.1, 46.4) [B]--> Here exepted (0.0, 45.0, 45.0)[/B]
UnityEngine.Debug:Log(Object)
**********************************************************/
Maybe I am doing something wrong with the quaternion?c#vector3quaternionWed, 20 May 2020 04:02:50 GMTbartifix(Solved) Aligning player to surface while still maintaining look direction
http://answers.unity.com/questions/1732431/aligning-player-to-surface-while-still-maintaining.html
Let's assume I have a sphere that can hover, so it has an offset from the ground. What I want is to simply rotate the sphere to match the normals of whatever is under it on the X and Z-axis, but still be able to rotate it to the direction in which it is travelling on the Y-axis. I have tried a few things that I found here on the forum and [2] seemed promising but unfortunately, it did not work.
<br><br>
RaycastHit hit;
if (Physics.Raycast(body.position, Vector3.down, out hit, 10, layerMask))
{ }
Quaternion groundTilt = Quaternion.FromToRotation(Vector3.up, hit.normal);
body.rotation = Quaternion.Euler(0, currentMovementDirection.y, 0);
body.rotation = groundTilt * body.rotation;
<br>Here is a diagram of what I want, seen from top and side views.
![alt text][1]
references:
[1] https://answers.unity.com/questions/1347986/rotating-a-player-to-match-terrain-slope.html
[2] https://forum.unity.com/threads/rotating-an-object-along-the-terrains-normal-whilst-looking-at-a-position.93570/
[1]: /storage/temp/159882-movement.pngrotationquaternioneuleranglesnormalsTue, 19 May 2020 11:24:30 GMTSteenPetersenQuaternion relative difference problem
http://answers.unity.com/questions/1732285/quaternion-relative-difference-problem.html
I have some code that updates an objects euler angles based on a parent rotation and an old rotation. I have it currently working as intended using euler angles, but it suffers from gimbal lock, which is why I'm trying to convert the code to Quaternions. Here's the code:
`newEuler = parentTransform.eulerAngles + (transform.eulerAngles - oldEuler);
transform.eulerAngles = newEuler;
oldEuler = parentTransform.eulerAngles;`
Because I'm subtracting the oldEuler from the current rotation, then adding the parent rotation, I thought I could simply replace the code with this:
`newRotation = parentTransform.rotation * (transform.rotation * Quaternion.Inverse(oldRotation));
transform.rotation = newRotation;
oldRotation = parentTransform.rotation;`
But this does not give the expected result at all. Any pointers here?rotationphysicsquaternionTue, 19 May 2020 00:31:35 GMTan-Online-UserRigidbody 2d rotation will count as float
http://answers.unity.com/questions/1732243/rigidbody-2d-rotation-will-count-as-float.html
Hi I have an error saying
<br><br>
error CS1503: Argument 1: cannot convert from 'float' to 'UnityEngine.Quaternion'
<br><br>
Below is my code
<br><br>
Vector2 _networkPosition;
<br>
Quaternion _networkRotation;
<br>
Rigidbody playerrigid;
<br><br>
void Start ()<br>
{
<br>
     playerrigid = GetComponent();
<br>
}
<br><br>
public void FixedUpdate()
<br>
{
<br>
    if (!PV.IsMine)
<br>
    {
<br>
        playerrigid.position = Vector2.MoveTowards(playerrigid.position, _networkPosition, Time.fixedDeltaTime);
<br>
<br>
        playerrigid.rotation = Quaternion.RotateTowards(playerrigid.rotation, _networkRotation, Time.fixedDeltaTime * 100.0f);
<br>
     }
<br>
}
<br><br><br>
the line 165 is the playerrigid.rotationquaternionunity 2dphotonfloatMon, 18 May 2020 21:32:30 GMTItsmeKerboyQuaternion Lerp when using a raycast.
http://answers.unity.com/questions/1732141/quaternion-lerp-when-using-a-raycast.html
Hello,
I have a Topdown game where I use my mouse pointer to make my character look into different directions. For that I use a racycast and the LookAt function, but I would like to add a turnspeed to my character so it's not so snappy.
I have been looking into Quaternion.Lerp but each time I implement it on my code, my character just turns frenetically and in the wrong axis.
This is my basic code to look at my pointer
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, Mathf.Infinity))
{
transform.LookAt(new Vector3(hit.point.x, transform.position.y, hit.point.z));
}
Is there a way I can use my hit.point to turn with Quaternion.Slerp?
This is the code I tried that makes my character just turn frenetically and also lie down instead of standing up.
void PlayerRotation()
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, Mathf.Infinity))
{
//transform.LookAt(new Vector3(hit.point.x, transform.position.y, hit.point.z));
Vector3 distance = hit.point - transform.position;
distance.y = 0;
Quaternion targetRotation = Quaternion.LookRotation(distance);
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, Time.deltaTime * 1);
}c#raycastquaternionMon, 18 May 2020 17:00:39 GMTweekywhawhaHow to rotate object in a few axis in turn
http://answers.unity.com/questions/1731328/how-to-rotate-object-in-a-fex-axis-in-turn.html
Hello guys. I have a cube in scene. I need to rotate it by 90 dgr in X axis by pressing 'left arrow key', and then to rotate it by 90 dgr in Z axis by pressing 'up arrow key'. It's working OK, but when i want to rotate it again in X axis, it rotates in wrong way. I understand that while rotating the cube I rotate its local axis and THAT'S WHY third and following rotating goes wrong. But I don't know how to cope with it, considering i need to be able to rotate the cube as many times as I want. Here is my code:
public void DebugRotate(int dir)
{
Vector3 axis = Vector3.zero;
switch (dir)
{
case 3:
axis = Vector3.left;
break;
case 2:
axis = Vector3.right;
break;
case 0:
axis = Vector3.forward;
break;
case 1:
axis = Vector3.back;
break;
}
if (!DOTween.IsTweening(transform))
transform.DORotateQuaternion(transform.rotation * Quaternion.AngleAxis(angle, axis), 1 / rotationSpeed);
}
For all, who doen't know what's 'DoRotateQuaternion' function in transform - this is Tweening plugin "DOTween". In this example it just make a transition from it's current rotation to the one that is in the first parameter of 'DoRotateQuaternion'.
And here is GIF of what happening there. Firstly I press 'Right, Left, Forward, Back' buttons to show you that for one rotation it works OK. But then it rotates wrong.
![alt text][1]
I'm trying to search this problem all day, but dunno in what direction to go. Thank you!
[1]: /storage/temp/159640-ezgifcom-resize.gifquaternionrotation axisMon, 18 May 2020 06:05:31 GMTJohnJoymanHelp! Stuck with this rotation automation! I got this automation to work for position and localScale, but them damn Quaternions...
http://answers.unity.com/questions/1731645/help-stuck-with-this-rotation-automation-i-got-thi.html
everything in the code reads out fine except for the line
Quaternion sineWave = Mathf.Sin (cycles * tau);
It says I cannot implicitly convert type float to quaternion.
Any ideas? Even the tinniest insight would be greatly appreciated! :)
public class Oscillator3 : MonoBehaviour
{
[SerializeField] Quaternion rotationScale;
[Range(0, 1f)] [SerializeField] Quaternion rotationLever;
[SerializeField] float period;
Quaternion initRotation;
void Start()
{
initRotation = transform.rotation;
}
void Update()
{
float cycles = Time.time / period;
const float tau = Mathf.PI * 2;
Quaternion sineWave = Mathf.Sin(cycles * tau);
rotationLever = sineWave;
Quaternion rotAmount = rotationLever * rotationScale;
transform.rotation = initRotation * rotAmount;
}rotationquaternionfloatautomationSun, 17 May 2020 08:47:12 GMTAdamOcheriCan't make smooth rotation using joystick
http://answers.unity.com/questions/1730737/cant-make-smooth-rotation-using-joystick.html
I tried to do smooth rotation using joystick
this code works almost like I want, but when i take my hand from joystick,character always turns in one direction
I use free joystick pack asset
here is my code:
public void FixedUpdate()
{
Vector3 direction = Vector3.forward * joystick.Vertical + Vector3.right * joystick.Horizontal;
rb.AddForce(direction * speed * Time.fixedDeltaTime, ForceMode.VelocityChange);
transform.Translate(Vector3.forward * forwardspeed);
Quaternion LookRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Lerp(transform.rotation, LookRotation, Time.deltaTime * (degreesPerSecond / 360f));c#quaternionsmoothThu, 14 May 2020 23:16:37 GMTAlex656How to use quaternions to apply an offset to a rotation to calibrate a controller
http://answers.unity.com/questions/1730249/how-to-use-quaternions-to-find-apply-an-offset-to.html
I have a tracker attached to a players foot.
I want to be able to calibrate the system so that when the player has their foot flat on the floor the VR foot will be flat too.
----------
I know the world rotation of the flat foot in VR and have defined it as `Vector3 flatFootRotation`
The world rotation of the tracker when the foot is flat is given by `tracker.rotation` at the time of calibration.
First, I determine the offset between the tracker and the foot:
offset = Quaternion.FromToRotation( tracker.rotation * Vector3.forward, Quaternion.Euler(flatFootRotation) * Vector3.forward);
From then on, I set the rotation of the foot according to the trackers rotation, plus an offset.
VRfoot.rotation = tracker.rotation*offset;
When the rotation of the tracker is unchanged from the calibration step, I expect that the VR foot will be flat on the floor. This does not happen and the foot has an unexpected rotation.
----------
I have tried reversing the order of all of these operations and have also tried using the inverse instead. Nothing works.rotationquaterniontrackingquaternionsrotationsThu, 14 May 2020 12:57:28 GMTjf1116screw changes direction of screwdriver
http://answers.unity.com/questions/1730251/screw-changes-direction-of-screwdriver.html
While trying to write code for a screw but I seem to be having an issue with the screw is not rotating the same direction as the screw driver all the time. The set up is based on the screwdriver tip being a trigger. An invisible box takes the place of the slot where the screwdriver tip should fit. It shouldn't matter but this is a VR related project even though it doesn't appear here. There is other code I am trying to implement for the inserting of the screwdriver not being the correct rotation to insert but I will get to that when the first part is working. My apologies if the code has some syntax errors, I have to retype the code since it is on a pc with no internet access.
bool driverInserted;
float tipRotation;
GameObject parentScrew;
GameObject tip;
void Start () {
parentScrew = transform.parent.gameObject;
}
void Update () {
tipRotation = Mathf.Abs(tip.transform.eulerAngles.z)
parentScrew.transform.eulerAngles = new Vector3 (transform.eulerAngles.x,transform.eulerAngles.y, tipRotation)
}
void OnTriggerEnter (Collider other) {
if(other.gameObject.name.Contains("Tip"))
{
tip = other.gameObject;
driverInserted = true;
}
}
void OnTriggerExit () {
tip = null;
driverInserted = false;
}rotationquaternionrotateeuleranglesWed, 13 May 2020 21:43:09 GMTGoliath520How i can rotate an Object with a Quaternion and a Vector3 at once?
http://answers.unity.com/questions/1730174/how-i-can-rotate-an-obkect-with-a-quaternion-and-a.html
Vector3 rotation;
void Update()
{
Vector3 Rot = new Vector3();
rotation.x = Rot.x;
rotation.y = Rot.y;
// Rot is the Vector which turn the gameobject
//rotaion is there becauseVector Rot would be Zero
uprotation = -move.y * 2 * uspeed;
Rot.y = move.x * uspeed;
Rot.x = uproation;
this.transform.Rotate(Rot * Time.deltaTime);
if(turntoright)
{
rigthrot = Mathf.Lerp(rigthrot, 70, 0.005f);
rotation.z = rigthtrot;
}
else
{
rigthrot = Mathf.Lerp(rigthrot, 0, 0.005f);
}
transform.rotation = Quaternion.Euler(rotation);
}
I want to rotate the Object in there direction who he is facing and not turn to Zero, zero. Thats why i used the vector rotation but it does not work
sorry for my bad EnglishrotationquaternionWed, 13 May 2020 18:20:39 GMTSpatenDeamonDirection of rotation
http://answers.unity.com/questions/1727654/direction-of-rotation-1.html
Hi guys, I have one question...
How to fix the direction of rotation?
* this is my code :)
this.transform.rotation = Quaternion.Lerp(this.transform.rotation, Quaternion.LookRotation(-moveDir), Time.deltaTime * 8);
My character rotates randomly..
Sometimes left,
Sometimes right...
I want to determine the direction of rotation.quaterniondirectionlookrotationrotaionThu, 07 May 2020 15:18:11 GMTEEEEEIISomething that needs to work but apparently not
http://answers.unity.com/questions/1727478/something-weird-about-my-c-script.html
if (Input.GetMouseButtonUp(0) || player.transform.position != offset)
{
draging = false;
gameObject.GetComponent<PolygonCollider2D>().isTrigger = true;
}
if (transform.rotation.z <= 0)
{
draging = false;
transform.rotation = Quaternion.Euler(0, 0, 0.1f);
draging = true;
}
if (transform.rotation.z >= 180)
{
draging = false;
transform.rotation = Quaternion.Euler(0, 0, 179.9f);
draging = true;
}
It happens to work for the first and second if statement but when I say if(transform.rotation.z >= 180) the code transform.rotation does not rotates to 179.9. Does anyone know why this isn't working?
@Hellium @AwesomeFaceHDrotationquaternionif-statementsThu, 07 May 2020 07:18:24 GMTsychoi461How to get object to walk around on mesh sideways and upside down
http://answers.unity.com/questions/1727402/fixing-this-script-to-make-objects-move-upside-dow.html
Trying to get objects to move around things sideways and upside down... like a bug would walk on a ceiling or wall...
<br><br>
https://gyazo.com/b47756e44c7a8b03384c378cda6d0081
<br><br>
The green lines in the gif are projected normals from the collision point, and the blue line is the downward raycast from the movable object. Right now I have a convex mesh collider on the big orange capsule and no collider on the green movable object.
<br><br>
So far I am raycasting down from -transform.up and then trying to rotate the object to the normal of the collision point in FixedUpdate... I get this really jittery result where it seems like it kind of works but something is off.
<br><br>
Any help smoothing this out and getting it to work correctly?
<br><br>
public class WalkAnywhere : MonoBehaviour
{
public float downRayDistance = 10;
public Vector3 downDirection;
void Update()
{
downDirection = -transform.up;
Debug.DrawRay(transform.position, downDirection * downRayDistance, Color.blue);
var downRay = new Ray(transform.position, downDirection * downRayDistance);
RaycastHit downRayInfo;
Physics.Raycast(downRay, out downRayInfo, downRayDistance, 1);
Debug.Log(downRayInfo.point);
Debug.Log(downRayInfo.normal);
Debug.DrawLine(downRayInfo.point, downRayInfo.point + downRayInfo.normal, Color.green, 4, false);
positionOnTerrain(downRayInfo);
}
void positionOnTerrain(RaycastHit downRayInfo)
{
Vector3 normal = downRayInfo.normal;
Vector3 point = downRayInfo.point;
Quaternion targetRotation = Quaternion.FromToRotation(transform.up, normal);
Quaternion finalRotation = Quaternion.RotateTowards(transform.rotation, targetRotation, 90);
transform.rotation = finalRotation;
transform.position = point + transform.up;
}
}raycasttransformquaternionThu, 07 May 2020 06:24:23 GMTF1nchesRotating object to face target, while being rotated to match terrain slope
http://answers.unity.com/questions/1727069/rotating-object-to-face-target-while-being-rotated.html
![alt text][1]
In the image above
- the red vector is the spider's forward vector
- the blue vector is the vector representing the direction between the spider and it's target
In the code below, `orientation` is a vector that's representing the normal of the terrain, so that the spider gets aligned to it:
<code>
Quaternion rotationNeeded = Quaternion.FromToRotation(Vector3.up, orientation);
transform.rotation = Quaternion.RotateTowards(
transform.rotation,
rotationNeeded,
RotationSpeed * Time.deltaTime
);
</code>
My issue is that I cannot manage to make the spider face its target... When I add any code that would make it rotate towards it, then it's not aligned with the terrain's normals...
[1]: https://i.imgur.com/AGOJTT9.png?1rotationterrainquaternionlookatnormalWed, 06 May 2020 10:24:46 GMTniuagehow to change player rotation in topdown view game
http://answers.unity.com/questions/1725916/how-to-change-player-rotation-in-topdown-view-game.html
hi I'm making a top down view game with basic player controls as I'm still fairly new to unity. I'm trying to get the player to rotate to face the direction they will move in. I've tried a lot of different ways to try and get it to work from things I've researched myself but just cant seem to get it to work properly I would really apricate if someone could help me out with this here is the current player movement method I'm using but it doesn't rotate at all
void PlayerMovement()
{
if (spawnmanagerX.isGameActive)
{
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.eulerAngles.Set(0, rotateLeft, 0);
transform.position += transform.forward * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.RightArrow))
{
transform.eulerAngles.Set(0, rotateRight, 0);
transform.position += transform.forward * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.UpArrow))
{
transform.eulerAngles.Set(0, rotateUP, 0);
transform.position += transform.forward * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.DownArrow))
{
transform.eulerAngles.Set(0, rotateDown, 0);
transform.position += transform.forward * speed * Time.deltaTime;
}
}
}rotationquaternioneuleranglestopdownSun, 03 May 2020 16:34:18 GMTdmfx9LookAt whilst traversing a sphere
http://answers.unity.com/questions/1725881/lookat-whilst-traversing-a-sphere.html
Hi,
I have a situation where I have an object that is on a sphere. Imagine the red dot is the object, and the green dot is where the object is facing.
![alt text][1]
[1]: /storage/temp/158407-diag1.jpg
I have code in place to allow the player to click on a point on the sphere and the object will move there. I now want the object to be facing the direction that it is moving. Initially I just went with:
object.LookAt(vecNextPointInPath)
However, this makes the object tilt in weird ways as it moves. I want to make sure that the top of the object is always facing upwards of the sphere as well as this LookAt. I am able to make it do this, by setting
transform.up = transform.position
however when I do this in tandem with the LookAt, the LookAt seems to be stomped over and it stays facing the same direction no matter which direction it is moving.
Does anyone have a solution to this? I imagine there is something with maths/quaternions that I've not figured out yet.
Thanks.quaternionlookatsphereupSun, 03 May 2020 14:57:58 GMTAlexSharpeDevSmooth look at
http://answers.unity.com/questions/1725876/smooth-look-at-1.html
Hello, I want to create a smooth **look at** for my character controller, my character must lock at the direction that he walks, but using the **look at** the result it's a trash, I also tried to use **Quaternion.lerp** and **quaternion.LookRotation**, but using this method, when I release the walk button my character don't stay in the rotation that's I leave him. Is there any way to fix this?
edit: My code
CharacterController character;
public Transform cameraDir;
Vector3 movement = cameraDir.transform.forward * moveY * 10 + cameraDir.transform.right * moveX * 10;
character.Move(movement * Time.deltaTime);
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(movement), 15*Time.deltaTime);
Ps: sorry for by bad english, I'm not a native english speaker and I can't think about anything else because I didn't sleep in last night.rotationquaternionlookatsmoothSun, 03 May 2020 14:43:17 GMTMaou_