Rotating raycast2D back and forth with object - c#

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

Related

Rotation off by 90 degrees unity

I am trying to rotate my 2d object around my mouse. This is the code I have:
void Update()
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = mousePosition - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0, angle);
// Debug.Log(angle);
}
My object, which is an arrow, is by default pointing down, so before I start the script I set its z rotation to 90, so it faces right. If I delete the transform.rotation line, the angle shown will be right, when my cursor is above it says 90, in the left it says 180 etc. So my question is: Why do I need to add 90 degrees to angle to make this actually work? Why doesn't this version work?
Mathf.Atan2(Also see Wikipedia - Atan2)
Return value is the angle between the x-axis [=Vector3.right] and a 2D vector starting at zero and terminating at (x,y).
It would work as expected if your arrow by default would point to the right but yours is
by default pointing down
you could simply add the offset rotation on top like
transform.rotation = Quaternion.Euler(0, 0, angle + 90);
Alternatively if you need this for multiple objects with different offsets either use a configurable field like
[SerializeField] private float angleOffset;
...
transform.rotation = Quaternion.Euler(0, 0, angle + angleOffset);
Or you could rotate it manually to face correctly to the right before starting the app and store that default offset rotation like
private Quaternion defaultRotation;
private void Awake ()
{
defaultRotation = transform.rotation;
}
and then do
transform.rotation = defaultRotation * Quaternion.Euler(0, 0, angle);

I have problem with rotation; rotatetoToTarget;

I want to 2dgameobject turns toward to target 2dgameobject
I have a Method - rotate to target.
Code:
Quaternion rawRoation = Quaternion.Slerp(transform.rotation,
Quaternion.LookRotation(Player.GetComponent<Transform>().position - transform.position),
10*Time.deltaTime);
transform.rotation = new Quaternion (0, 0, rawRoation.z, rawRoation.w);
Problem - WHen target's position.x < this.object.transform.position.x(1) - rotation breaks..
else(2) - all right.
1 -
enter image description here
2 - enter image description here
The problem is this line of code: transform.rotation = new Quaternion (0, 0, rawRoation.z, rawRoation.w);
I don't know what you want to achieve, but if you want to nullify the x and y rotation use:
transform.rotation = Quaternion.Euler(0.0f, 0.0f, rawRoation.eulerAngles.z);
Example of what your code does:
// Start is called before the first frame update
void Start()
{
Quaternion q1 = new Quaternion(0.3f, 0.7f, 0.4f, 0.5f);
Quaternion q2 = new Quaternion(0.0f, 0.0f, 0.4f, 0.5f);
Debug.Log(q1.eulerAngles);
Debug.Log(q2.eulerAngles);
}
And here the output:
q1: (344.8, 100.3, 59.1)
q2: (0.0, 0.0, 77.3)
Please have a look at the math of quaternions
Edit - 2D LookAt:
Your code does not work like you want because you are in 2D. If you want to look at a target with an x-position less than your object's in 3D you have to do a rotation around the y-axis by 180deg which in 2D is not a valid rotation. You cannot. You do this y-rotation to prevent that the object is upside down. but in 2D you cannot do such a rotation.
You have to choices:
If your camera looks from the side and your object can be upside down use your modified code and also set the x-scale to -1 if the targets x-position is less.
If your camera looks from top down use the following
code:
Code for upside down view:
// Update is called once per frame
void Update() {
Vector3 targetDir = target.position - transform.position;
float angle = Mathf.Atan2(targetDir.y, targetDir.x) * Mathf.Rad2Deg;
Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * 10);
}

Unity 3d, point object towards mouse (3d space)

I searched around for a while but I couldn't figure out how to solve this nasty bug. I am using a top down view (pointing towards -z), basically 2d with 3d objects and camera in perspective mode.
I need to orient an object towards the mouse , ignoring the z aspect, as everything moves on the same plane.
I am using the following code:
Vector3 mouseToWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition + new Vector3(0, 0, 1f));
mouseToWorld.z = 0f;
Vector3 difference = mouseToWorld - transform.position;
difference.Normalize();
float angle = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, angle - 90);
Unfortunately it only works when the object is still, and breaks as soon as the velocity is > 0;
Any hint would be appreciated :)
p.s. I am adding 1 to the z and then resetting it, because otherwise the mouseToWorld is constantly 0 wherever I move the pointer.
Perhaps it breaks because the velocity vector and the mouse direction aren't the same.
the following script will make an arrow follow the mouse, It's basically the same as yours except it updates the position as well:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowMouse : MonoBehaviour {
public float moveSpeed = 0.01f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.position = Vector2.Lerp(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition), moveSpeed);
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
difference.Normalize();
float rotation_z = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotation_z);
}
}
Thanks for the answer! I figured out you need to subtract the distance between the player and the camera to the initial mouse position:
Vector3 mouseToWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition - new Vector3(0, 0, Camera.main.transform.position.z));
Here the working script:
Vector3 mouseToWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition - new Vector3(0, 0, Camera.main.transform.position.z));
//Debug.DrawLine(transform.position, mouseToWorld);
mouseToWorld.z = 0f;
Vector3 difference = mouseToWorld - transform.position;
difference.Normalize();
float angle = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, angle - 90);

How do I make a 2D object face the direction it is moving like drifting

As shown in the picture above, I have two GameObjects: the car and the circle. The car follows the circle, and the circle is moving with the cursor. Currently, my car is following the circle from a distance. When the circle moves along the x-axis, I want to rotate the car like it's drifting.
Here is my car follow script:
public class Follow : MonoBehaviour
{
public Transform leader;
public float followSharpness = 0.1f;
Vector3 _followOffset;
void Start()
{
// Cache the initial offset at time of load/spawn:
_followOffset = transform.position - leader.position;
}
void LateUpdate()
{
// Apply that offset to get a target position.
Vector3 targetPosition = leader.position + _followOffset;
//GetComponent<Rigidbody2D>().rotation = 1.5f;
// Keep our y position unchanged.
//targetPosition.y = transform.position.y;
// Smooth follow.
transform.position += (targetPosition - transform.position) * followSharpness;
}
}
You could try to use Transform.LookAt:
void LateUpdate()
{
Vector3 targetPosition = leader.position + _followOffset;
transform.position += (targetPosition - transform.position) * followSharpness;
transform.LookAt(leader);
}
Disclaimer: I'm not able to test that this code works right now, you'll have to try it out and see if it produces the desired result.
So from what you described, is you want to make the car always facing the cursor, so it is always "looking at" the cursor, here is how you can do it:
Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
diff.Normalize();
float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rot_z - 90);
From Answer: LookAt 2D Equivalent ?

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