Converting FPS ground camera to FPS free flying camera - c#

I have implemented a camera in my OpenGL(openTk) project
//Move(0f, 0.1f, 0f); } Forward
//Move(-0.1f, 0f, 0f); } Left
//Move(0f, -0.1f, 0f); } Back
//Move(0.1f, 0f, 0f); } Right
//Move(0f, 0f, 0.1f); } Up
//Move(0f, 0f, -0.1f); } Down
public static void Move(float x, float y, float z)
{
Vector3 offset = new Vector3();
Vector3 forward = new Vector3((float)Math.Sin((float)Orientation.X), 0, (float)Math.Cos((float)Orientation.X));
Vector3 right = new Vector3(-forward.Z,0,forward.X);
offset += x * right;
offset += y * forward;
offset.Y += z;
offset.NormalizeFast();
offset = Vector3.Multiply(offset, MoveSpeed);
Position += offset;
}
Where "Orientation" is the x,y of the direction the camera is facing. "Position" is the position of the Camera in the world, and "MoveSpeed" is float.
This camera works great. But it is ground based. By this I mean that only the x value of the camera orientation affects movement direction. The y value does not. I want to make a free flying camera so if you look up and press forward the camera will fly into the air.
I tried changing the forward declation to:
Vector3 forward = new Vector3((float)Math.Sin((float)Orientation.X), (float)Math.Sin((float)Orientation.Y), (float)Math.Cos((float)Orientation.X));
This partially works, the camera now can fly into the air. But its not right, the camera is moving the same forward amount no matter how far "up" you tilt it. The up is not replacing some of the forward, its being added onto it.
I hope this explanation makes sense.
Thanks

You can do something like this:
First get the forward vector from Orientation (you can use this for your Camera.LookAt as well)
public Vector3 getForward(Vector2 Orientation)
{
Vector3 forward = new Vector3(0, 1, 0);
//X axis rotation
forward.Z = (float)Math.Sin((float)Orientation.Y);
forward.Y = (float)Math.Cos((float)Orientation.Y);
//Z axis rotation
forward.X = forward.Y*(float)Math.Sin((float)Orientation.X);
forward.Y = forward.Y*(float)Math.Cos((float)Orientation.X);
return forward;
}
And then move your camera with:
public void Move(float horizontal, float strafe)
{
Vector3 forward=getForward(Orientation);
//forward vector projected on XoY plane and rotated 90 degrees
Vector3 leftXoY = new Vector3(-forward.y ,forward.x,0);
Vector3 moveDirection = Vector3.Multiply(forward,horizontal)+Vector3.Multiply(leftXoY,strafe);
moveDirection.Normalize();
Position += Vector3.Multiply(moveDirection,MoveSpeed);
}
So if you call move(1,-1); will move the camera forward (along the forward vector) and strafe right.

I have found the solution after fiddling with it for a long time. I do not know if this is an efficient way to do it or not but it does work.
public static void Move(float x, float y, float z)
{
Vector3 CameraTargetVector;
CameraTargetVector.X = (float)(Math.Sin((float)Orientation.X) * Math.Cos((float)Orientation.Y));
CameraTargetVector.Y = (float)Math.Sin((float)Orientation.Y);
CameraTargetVector.Z = (float)(Math.Cos((float)Orientation.X) * Math.Cos((float)Orientation.Y));
Vector3 offset = new Vector3();
offset += x * new Vector3(-CameraTargetVector.Z, 0, CameraTargetVector.X);
offset += y * CameraTargetVector;
offset.Y += z;
offset.NormalizeFast();
Position += Vector3.Multiply(offset, MoveSpeed);
}

Related

How to use LookRotation to rotate an object based on hand positions?

I'm creating an interaction system for a VR game and I'm struggling with two hand interactions. I'm using the Quaternion.LookRotation() method to generate the rotation of the grabbed object based on the positions and rotations of the hands. The forward part is pretty simple:
Vector3 fwd = (primaryHand.position - secondaryHand.position).normalized;
The "up" part is what I have difficulty with. Initially I tried using the average up direction of both hands:
Vector3 avgUp = Quaternion.Slerp(primaryHand.rotation, secondaryHand.rotation, 0.5f) * Vector3.up;
There is an issue with this approach: the hand's up vector might get aligned with the fwd vector, which causes the object to flip over when it goes over it. Here is a simple illustration of the problem:
The light green arrows represent the up direction of the hands, while the dark green is the calculated direction used as an argument for the LookRotation() method.
The obvious solution seems to be to pick a different fixed vector instead of "up", one which won't be so easily aligned with the fwd vector. In the example it could be a vector aligned with the fingers. But keep in mind that there are no restrictions on initial hand rotation so no matter which vector you choose the hands can always happen to be rotated so that the vectors align. And even if you pick the an optimal vector dynamically (one that is perpendicular to fwd), it's still at best 90 degrees from aligning with fwd.
To solve this I tried restricting the direction to the values which don't cause problems but this caused another issues (I had difficulties with determining which values are ok and which should be discarded). I feel like I'm doing something wrong here, is there any better solution to this problem?
You can calculate the delta rotations of the hands and apply it to the "base up" of the object (the new up if we only take into account the change in position of hands...which will of course be orthogonal to the axis of the object). Then determine the change in angle that results in that up being rotated with each hand. Average those angles out, then apply those angles with the hand-hand axis using Quaternion.AngleAxis to the "base up" from earlier. Then you have your forward and up for Quaternion.LookRotation).
Below is an example of how you can use this, including VR hand noise simulation. To see the test, create a new scene in unity and attach this to the camera and it will build the scene on play start. There is a grip/release gui that will appear in Play view. You can adjust the hand rotation in Scene view
Vector3 leftHandPosCurrent;
Vector3 rightHandPosCurrent;
Vector3 worldAxisPrev;
Quaternion leftHandRotPrev;
Quaternion leftHandRotCurrent;
Quaternion rightHandRotPrev;
Quaternion rightHandRotCurrent;
bool isGripping;
bool firstFrameGripping;
Rigidbody grippedRB;
Transform leftHand;
Transform rightHand;
Quaternion targetRot;
/*
* On subsequent frames of gripping, calculate deltas in positions and
* rotations, average out the hand's effects, then apply them to the gripped
* object
*/
void HandleGrippedRot()
{
Vector3 worldAxisCurrent = rightHandPosCurrent - leftHandPosCurrent;
if (!firstFrameGripping)
{
Vector3 prevUp = targetRot * Vector3.up;
// we haven't moved the transform based on the hands yet, so
// find the new up would be ignoring hand rotations
Vector3 newUp = Quaternion.FromToRotation(worldAxisPrev,
worldAxisCurrent) * prevUp;
float leftHandAngle = GetDegRot(newUp, leftHandRotPrev,
leftHandRotCurrent, worldAxisCurrent);
float rightHandAngle = GetDegRot(newUp, rightHandRotPrev,
rightHandRotCurrent, worldAxisCurrent);
float avgAngle = (leftHandAngle + rightHandAngle) * 0.5f;
newUp = Quaternion.AngleAxis(avgAngle, worldAxisCurrent) * prevUp;
targetRot = Quaternion.LookRotation(worldAxisCurrent,
newUp);
}
else
{
firstFrameGripping = false;
}
leftHandRotPrev = leftHandRotCurrent;
rightHandRotPrev = rightHandRotCurrent;
worldAxisPrev = worldAxisCurrent;
}
/*
* Given the "up" of the object without taking hand rotations into account
* and the axis, determine how a hand's delta rotation affects that up
* around the axis and return the angle of that rotation
*/
float GetDegRot(Vector3 baseUp, Quaternion prevHandRot, Quaternion curHandRot,
Vector3 axis)
{
Vector3 adjUp = (curHandRot * Quaternion.Inverse(prevHandRot)) * baseUp;
adjUp = Vector3.ProjectOnPlane(adjUp, axis);
return Vector3.SignedAngle(baseUp, adjUp, axis);
}
void Update()
{
AddVRNoise(leftHand);
AddVRNoise(rightHand);
leftHandPosCurrent = leftHand.position;
rightHandPosCurrent = rightHand.position;
leftHandRotCurrent = leftHand.rotation;
rightHandRotCurrent = rightHand.rotation;
if (isGripping)
{
HandleGrippedRot();
}
}
void StartGrip()
{
if (isGripping) return;
isGripping = true;
firstFrameGripping = true;
// grippedTransform is set accordingly at some point
}
void EndGrip()
{
if (!isGripping) return;
isGripping = false;
}
/*
* example of using targetRot to move rb
*/
private void FixedUpdate()
{
if (!isGripping) return;
Quaternion delta = targetRot
* Quaternion.Inverse(grippedRB.transform.rotation);
delta.ToAngleAxis(out float angle, out Vector3 axis);
// convert to shortest angle form
if (angle > 180f)
{
axis = -axis; angle = 360f - angle;
}
grippedRB.angularVelocity = angle * 0.25f * axis;
}
/*
* just for testing purposes
*/
void Start()
{
leftHand = CreateHand(true);
leftHand.position = Vector3.left;
rightHand = CreateHand(false);
rightHand.position = Vector3.right;
CreateArrow();
}
/*
* just for testing purposes
*/
void AddVRNoise(Transform hand)
{
Quaternion noise = Random.rotation;
noise.ToAngleAxis(out float angle, out Vector3 axis);
angle = 100f * Time.deltaTime;
noise = Quaternion.AngleAxis(angle, axis);
Quaternion noisyRot = hand.rotation * noise;
hand.rotation = noisyRot;
}
/*
* just for testing purposes
*/
void OnGUI()
{
if (GUI.Button(new Rect(0, 0, 100, 50), "Grip"))
{
StartGrip();
}
if (GUI.Button(new Rect(100, 0, 100, 50), "Release"))
{
EndGrip();
}
}
/*
* just for testing purposes
*/
Transform CreateHand(bool isLeft)
{
string handName = isLeft ? "Left" : "Right";
GameObject hand = new GameObject($"{handName}hand");
GameObject palm = GameObject.CreatePrimitive(PrimitiveType.Cube);
palm.transform.localScale = new Vector3(0.5f, 0.2f, 1f);
palm.transform.SetParent(hand.transform);
GameObject thumb = GameObject.CreatePrimitive(PrimitiveType.Cube);
thumb.transform.localScale = new Vector3(0.2f, 0.1f, 0.1f);
thumb.transform.SetParent(hand.transform);
thumb.transform.localPosition = new Vector3(isLeft ? 0.32f : -0.32f,
0f, -.31f);
return hand.transform;
}
/*
* just for testing purposes
*/
void CreateArrow()
{
GameObject arrow = new GameObject();
GameObject body = GameObject.CreatePrimitive(PrimitiveType.Cube);
body.transform.localScale = new Vector3(1f, 1f, 5f);
body.transform.SetParent(arrow.transform);
GameObject head = GameObject.CreatePrimitive(PrimitiveType.Cube);
head.transform.SetParent(arrow.transform);
head.transform.localEulerAngles = Vector3.up * 45f;
head.transform.localPosition = new Vector3(0f, 0f, 2.5f);
grippedRB = arrow.AddComponent<Rigidbody>();
grippedRB.useGravity = false;
arrow.transform.position = 2f * Vector3.up;
}

Rotating raycast2D back and forth with object

I made a circle and attach a lazer box on top of it.
The lazer will fire a raycast to its upper y axis (straight up). I also add a line renderer to view it.
I want the raycast to rotate 90 degrees back and forth. Sort of like its scanning everything on top. My problem is that its not working properly. It does rotate back and forth but If I move the x position of the lazer object, the raycast will rotate in a weird angle.
Script for lazer object
public LineRenderer lineRenderer;
public LayerMask layerMask;
public float laserSpeed;
Vector3 pointA;
Vector3 pointB;
Vector3 castPosition;
RaycastHit2D rayCast;
float time;
void Start()
{
pointA = transform.eulerAngles + new Vector3(0f, 0f, 90f);
pointB = transform.eulerAngles + new Vector3(0f, 0f, -90f);
}
void Update()
{
time = Mathf.PingPong(Time.time * laserSpeed, 1);
transform.eulerAngles = Vector3.Lerp(pointA, pointB, time);
castPosition = new Vector3(transform.position.x, transform.position.y, transform.position.z);
rayCast = Physics2D.Raycast(castPosition, transform.TransformDirection(Vector2.up), 10f, layerMask);
lineRenderer.SetPosition(0, castPosition);
lineRenderer.SetPosition(1, transform.TransformDirection(Vector2.up) * 10f);
}
Using eulerAngles for continuous animations is quite "dangerous". Unity stores the rotations as Quaternion and there are multiple ways of how to represent these in euler space!
When you read the .eulerAngles property, Unity converts the Quaternion's internal representation of the rotation to Euler angles. Because, there is more than one way to represent any given rotation using Euler angles, the values you read back out may be quite different from the values you assigned. This can cause confusion if you are trying to gradually increment the values to produce animation.
To avoid these kinds of problems, the recommended way to work with rotations is to avoid relying on consistent results when reading .eulerAngles particularly when attempting to gradually increment a rotation to produce animation. For better ways to achieve this, see the Quaternion * operator.
so you should rather go for Quaternion and do e.g.
And then you are using transform.TransformDirection(Vector2.up) which is a direction and pass it to your line renderer as a position.
What you want there is rather the position combined from
transform.position + transform.up
So together it should probably rather be
public LineRenderer lineRenderer;
public LayerMask layerMask;
public float laserSpeed;
private Quaternion originalRotation;
private Quaternion minRotation;
private Quaternion maxRotation;
void Start()
{
originalRotation = transform.rotation;
minRotation = originalRotation * Quaternion.Euler(0, 0, -90);
maxRotation = originalRotation * Quaternion.Euler(0, 0, 90);
}
void Update()
{
// Note that Vector3 is a "struct" -> there is no need to manually use "new Vector3(transform.position.x, ...)"
var startPosition = transform.position;
lineRenderer.SetPosition(0, startPosition);
var factor = Mathf.PingPong(Time.time * laserSpeed, 1);
// instead of the eulers rather use Quaternion
transform.rotation = Quaternion.Lerp(minRotation, maxRotation, factor);
// "transform.up" basically equals using "transform.TransformDirection(Vector3.up)"
var rayCast = Physics2D.Raycast(startPosition, transform.up, 10f, layerMask);
if(rayCast.collider)
{
// when you hit something actually use this hit position as the end point for the line
lineRenderer.SetPosition(1, rayCast.point);
}
else
{
// otherwise from the start position go 10 units in the up direction of your rotated object
lineRenderer.SetPosition(1, startPosition + transform.up * 10f);
}
}

When I make an object face a mouse cursor in Unity it eventually offsets

I made a script that makes the player point towards the mouse cursor, but recently I discovered a bug. When I move the mouse cursor too much (An example being when I spin the mouse around the object in circles, causing the object to move around.), the object ends up pointing a bit off of where the mouse should be. As in, the cursor would signal the object to look at it, and the object ends up looking the slightest bit off, making it feel quite odd after maneuvering quickly. How can I make it so the object always faces the cursor, with no offsets, even when I move the cursor as much as possible.
private void LateUpdate()
{
Vector3 lookAtPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 mousePoint = new Vector3(lookAtPoint.x, lookAtPoint.y, 0);
float angle = getAngle(transform.position, mousePoint);
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0, 0, angle), 9f * Time.deltaTime);
float getAngle(Vector3 currentLocation, Vector3 mouseLocation)
{
float x = mouseLocation.x - currentLocation.x;
float y = mouseLocation.y - currentLocation.y;
return angle = Mathf.Rad2Deg * Mathf.Atan2(y, x);
}
}
Looks like it's down to the way that you are using Quaternion.Lerp(). In particular, the last parameter - it is meant to be a value between 0f and 1f which you supply, it does not auto-increment for you.
So to fix this issue, what you want to do is save off a float somewhere. When you move the mouse (mouse position has changed since last frame) then start that value at 0f again. Then increment it at some value every frame until it is equal to or greater than 1f.
Doing this will not only fix your bug. It will, depending on how fast your increment, give you a smooth rotation effect. Below is an example.
internal class SomeClass : MonoBehaviour
{
private float lerpAmount = 0f;
private Vector3 cachedMousePosition = Vector3.zero;
private void LateUpdate()
{
var mousePosition
= Camera.main.ScreenToWorldPoint(Input.mousePosition)
* new Vector3(1, 1, 0);
bool recalculateRotation = false;
if (this.cachedMousePosition != mousePosition)
{
this.lerpAmount = 0f;
recalculateRotation = true;
}
if (this.lerpAmount < 1f)
{
this.lerpAmount = Mathf.Min(this.lerpAmount + Time.deltaTime, 1f);
recalculateRotation = true;
}
if (recalculateRotation)
{
float angle = getAngle(transform.position, mousePoint);
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0, 0, angle), this.lerpAmount);
}
float getAngle(Vector3 currentLocation, Vector3 mouseLocation)
{
float x = mouseLocation.x - currentLocation.x;
float y = mouseLocation.y - currentLocation.y;
return angle = Mathf.Rad2Deg * Mathf.Atan2(y, x);
}
}

my y rotation keeps changing even though i'm not changing it

i am trying to rotate its x and z axis to the mouse position while not changing the y. for some reason the y keeps changing!!!
my current code looks like this
public float moveSpeed = 5;
public float maxMoveSpeed = 15;
CharacterController body;
// Start is called before the first frame update
void Start()
{
body = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
Vector3 point = new Vector3(hit.point.x, 0, hit.point.z);
print(point);
transform.LookAt(point);
}
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Vector3 moveDis = transform.forward * v * moveSpeed;
moveDis += transform.right * h * moveSpeed;
body.SimpleMove(moveDis);
}
for some reason if i remove the player controller it works fine!
i am trying to rotate its x and z axis
No you are not ^^
What you are doing is
Vector3 point = new Vector3(hit.point.x, 0, hit.point.z);
transform.LookAt(point);
where LookAt
Rotates the transform so the forward vector points at /target/'s current position.
which in most cases will rotate your object around the X and Y axis!
It is unclear what your actual goal would be in order to provide a possible solution to that, though.

Rotate cameran around a gameobject in unity3d

I want to rotate camera around an fbx object when a key is being pressed using unity 3d.How it do? I tried some examples but its not working. First i create a game object and add main camera child of it.
public class CameraOrbit : MonoBehaviour
{
public Transform target;
public float speed = 1f;
private float distance;
private float currentAngle = 0;
void Start()
{
distance = (new Vector3(transform.position.x, 0, transform.position.z)).magnitude;
}
void Update()
{
currentAngle += Input.GetAxis("Horizontal") * speed * Time.deltaTime;
Quaternion q = Quaternion.Euler(0, currentAngle, 0);
Vector3 direction = q * Vector3.forward;
transform.position = target.position - direction * distance + new Vector3(0, transform.position.y, 0);
transform.LookAt(target.position);
}
}
I dont have access to unity at the moment so i might have messed something up.
The idea is keep an angle that you change based on input. Create a Quaternion from the angle (the Quaternion say how to rotate a vector to a certain direction), then rotate a Vector to that direction. Starting from the targets position move in that direction a certain distance and then look at the targets position.
This only implements rotation around the y axis, if you want rotation around the x axis all you need is another angle variable and then change to this Quaternion.Euler(currentAngleX, currentAngleY, 0);

Categories