How can I make a GameObject point towards another GameObject in Unity? - c#

I tried this code but it doesn't work correctly.
Edit: LookAt makes the GameObject invisible
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyPoint : MonoBehaviour {
public float offset;
public Transform target;
private void Update()
{
Vector2 difference = target.position - transform.position;
float rotZ = Mathf.Atan(difference.y) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
}
}

You can use LookAt.
Rotates the transform so the forward vector points at target's current position.
transform.LookAt(target);
Simply place this on your objectA and in the target field drag&drop any other objectB → objectA's forward vector will always point towards objectB.
An alternative overwrite also takes a world position as Vector3 instead so you can also use
transform.LookAt(target.position);
which will basically do exactly the same thing.
If you need another axis pointing towards the target you can still use LookAt and afterwards Rotate. E.g. in order to not make the forward but rather the up Vector of the object point towards the target you can use
transform.LookAt(target);
transform.Rotate(Vector3.right * 90);

this thread is pretty old, but nonetheless i thought i might just pitch in. In line 13 you're using the wrong trig function. Using Mathf.Atan2(y, x) yields the arctangent y/x in the range of -π to +π, instead, you're using Mathf.Atan(y) which just does calculations based on y only and doesn't take into account the x value as well.
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg //Get arctangential of x and y and turn it into degrees with 180/π

Related

How to make a ground object follow a flying object in unity?

I'm trying to make an object on the ground follow a flying object, for example a drone leading a human (for now i'm just using shapes - a cube and a capsule). My cube follows the capsule like i desire but i want the cube to follow the capsule on the ground only, rather than go up on the y-axis with the capsule. Right now, it follows the capsule everywhere, I want the capsule to lead while the cube follows along on the ground.
I have done some research on Google and Youtube but I have not seen any results. Please let me know how I can achieve this.
This is the code script attached to the cube(ground object)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class follow_target : MonoBehaviour
{
public Transform mTarget;
float mSpeed = 10.0f;
const float EPSILON = 0.1f;
Vector3 mLookDirection;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
mLookDirection = (mTarget.position - transform.position).normalized;
if((transform.position - mTarget.position).magnitude > EPSILON)
transform.Translate(mLookDirection * Time.deltaTime * mSpeed);
}
}
If the ground is planar, you can just set the y component to 0 (or whatever the ground y vector is).
If the ground changes in topology, you can do a raycast down from the capsule to get the hit point (vector3). You can use the hit point y component for the height. After that you will need to set the cubes rotation so that it is aligned to the ground. You could do that with a raycast as well, there are a number of examples of that online.
I hope that helps get you in the right direction.
Assuming a flat ground on Y = 0
either make sure your objects sticks to the ground so set
private const float EPSILONSQR = EPSILON * EPSILON;
void Update()
{
var difference = mTarget.position - transform.position;
mLookDirection = difference.normalized;
if(difference.sqrmagnitude > EPSILONSQR)
{
// In general be aware that Translate by default moves in the
// objects own local space coordinates so you probably would rather
// want to use Space.World
transform.Translate(mLookDirection * Time.deltaTime * mSpeed, Space.World);
var pos = transform.position;
// reset the Y back to the ground
pos.y = 0;
transform.position = pos;
}
}
or simply already map the direction down on the XZ plane (ignoring any difference in Y) like
private const float EPSILONSQR = EPSILON * EPSILON;
void Update()
{
var difference = mTarget.position - transform.position;
mLookDirection = difference.normalized;
// simply ignore the difference in Y
// up to you if you want to normalize the vector before or after doing that
mLookDirection.y = 0;
if(difference.sqrmagnitude > EPSILONSQR)
{
transform.Translate(mLookDirection * Time.deltaTime * mSpeed, Space.World);
}
}

Trying to write a C# code to make a missile follow the player in Unity

I have been trying this for two days with no success. I cant figure out where I'm missing the point. All the missiles are moving towards the position of the target but not following it. The position remains fixed and all the newly created missiles come to this point instead of following the target.
Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HomingMissile : MonoBehaviour
{
private GameObject target; //changed to private
private Rigidbody rb;
public float rotationSpeed;
public float speed;
Quaternion rotateToTarget;
Vector3 direction;
private void Start()
{
target = GameObject.FindGameObjectWithTag("Player"); //uncommented this
rb = GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
//made some modifications
Vector3 direction = (target.transform.position - transform.position).normalized;
float angle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;//interchanged x and z
Quaternion rotateToTarget = Quaternion.Euler(0, angle, 0);
transform.rotation = Quaternion.Slerp(transform.rotation, rotateToTarget, Time.deltaTime * rotationSpeed);
Vector3 deltaPosition = speed * direction * Time.deltaTime;
rb.MovePosition(transform.position + deltaPosition);
}
}
I selected the target(transform) using the inspector.
I'm using Unity and C# obviously you know that.
What Im trying to achieve is that the missile should follow the position of the target in real time. And i can add the destroy code for the missile myself.
Note :
Please don't tag this as a duplicate. It is not.
The game is 2D where Y is always constant. Vertical axis is X and Horizontal axis is X. The objects are 3D. That's why I can't use rigidbody2D.
EDIT:
Code edited. The missile follows the target and also points to the direction of motion. How to make the missile make a circular rotation when it needs to rotate?
Firstly, consider:
Not modifying a rigidbody.velocity directly, as it will result in unrealistic behaviour
Using FixedUpdate() instead of Update() when controlling rigidbodies
Use rigidbody.movePosition() and rigidbody.moveRotation() instead. Here's an example:
Vector3 dir = (target.transform.position - transform.position).normalized;
Vector3 deltaPosition = speed * dir * Time.deltaTime;
rb.MovePosition(transform.position + deltaPosition);
Try out rigidbody.MoveRotation() yourself for practice.
Finally, understand that there are many ways to implement homing for missiles. Here's one that is commonly used in real life.
Edit: I will not recommend using rb.addForce() because if u try it out u will realise it is too indeterministic.

How Quaternion gets multiplied with a vector?

I am working on a third person shooter. And I have found this code. But I cant make no sense with it. First it is multiplying Quaternion with "Vector3.forward" and compiler is showing nothing. And also can you make me clear about the main logic of this code. I know memorizing the code is not a good habit. So can you explain me the code. And what does that Quaternion.euler does, is that for changing euler to quaternion.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour {
[SerializeField]
Transform target;
[SerializeField]
float distance;
[SerializeField]
float targetheight;
private float x = 0;
private float y = 0;
void LateUpdate()
{
y = target.eulerAngles.y;
Quaternion rotation = Quaternion.Euler(x, y, 0);
Debug.Log(rotation);
transform.rotation = rotation;
var postion = target.position - (rotation *Vector3.forward* distance + new Vector3(0, -targetheight, 0));
transform.position = postion;
}
}
Let's break it down:
y = target.eulerAngles.y;
This is Transform.eulerAngles() and gives you the current rotation of the target as Quaternion.
Then that rotation is reapplied to the target, but with the rotation around the Z-axis removed.
Quaternion rotation = Quaternion.Euler(x, y, 0);
Debug.Log(rotation);
transform.rotation = rotation;
This is Quaternion.Euler(x,y,z) and gives you a rotation from three degree values.
Last is the following calculation:
var postion = target.position - (rotation *Vector3.forward* distance + new Vector3(0, -targetheight, 0));
transform.position = postion;
Multiplying a Vector3 by a Quaternion means to apply the rotation to the vector. So in this case you'd rotate the forward vector based on the rotation of the target (without the Z-axis rotation, since we set that to 0 earlier). Then that resulting forward vector is multiplied by a certain distance to give us a point somewhere in front of the target's current facing direction and lowered according to the targetheight variable.
Lastly that calculation is subtracted from our own current position, basically performing a point reflection with the target being the point. The result is that we actually end up with a position that has a positive height (originally we were using a negative targetheight) and are behind the target's facing direction.

Why does my directional light only rotate from 90º to -90º (Unity 5.5)

I have tried both of these C#scripts to rotate my directional light:
using System.Collections;
using UnityEngine;
public class LightRotator : MonoBehaviour
{
void Update ()
{
transform.rotation = Quaternion.Euler(transform.eulerAngles.x + 1.0f,
transform.eulerAngles.y,
transform.eulerAngles.z);
}
}
and
using System.Collections;
using UnityEngine;
public class LightRotator : MonoBehaviour
{
void Update ()
{
transform.localEulerAngles = new Vector3(transform.localEulerAngles.x + 1.0f,
transform.localEulerAngles.y,
transform.localEulerAngles.z);
}
}
They both seem to function exactly the same: If I change transform.eulerAngles.y to transform.eulerAngles.y + 0.5f, the light will rotate along the y-axis, and the same works for the z-axis. However, when I try to do this with the x-axis, it will rotate until it hits 90º, at which point it will continue to attempt rotation but it immediately and continuously shoved back to 90º. If I reverse the direction, it does the same thing at -90º. For example, the rotation might be: 88.5,89.0,89.5,90.0, 90.5, 89.93, 90.24, 89.4, etc.
What is causing this clamping and how do I fix it?
I think this is what you are looking for: http://answers.unity3d.com/questions/187073/rotation-locks-at-90-or-270-degrees.html
In order to fix your problem, you need to use an additional vector, change it inside Update every frame, and then pass it to the eulerAngles propriety of the transform.
Vector3 vect = Vector3.zero;
float rotationSpeed = 10f;
void Start () {
vect = transform.eulerAngles; //Set the vect rotation equal to the game object's one
}
void Update ()
{
vect.x += rotationSpeed * Time.deltaTime;
//Pass unique eulerAngles representation to the object without letting Unity change it
transform.eulerAngles = vect;
}
This happens btw because there're multiple euler angles representation of a single physical rotation in the 3D space, and when you work directly on the eulerAngles propriety of the transform, Unity makes some work behind the scenes, which can lead to a gimbal lock.
Use Quaternions. It's what Unity3d uses internally and doesn't have any of the side effects of euler angles.
using System.Collections;
using UnityEngine;
public class LightRotator : MonoBehaviour
{
public Vector3 RotationAxis = Vector3.right;
Quaternion _startRotation;
float _rotationIncrement = 0;
void Start()
{
_startRotation = transform.rotation;
}
void Update ()
{
Quaternion rotationMod =
Quaternion.AngleAxis(_rotationIncrement, RotationAxis);
_rotationIncrement += 1;
transform.rotation = _startRotation * rotationMod;
}
}
However, you probably want to use something like Quaternion.RotateTowards or Quaternion.Lerp along with Time.time and a rate. You will get much smoother results that way.
if you only want to rotate along the X-axis then set the other axis as 0.

How do I get an object to rotate on only one axis?

I'm using Unity 5 (latest version), and I'm trying to make a conveyor belt type of thing. To do so I want to have cylinders rotate on the z-axis, and only the z-axis. How would I do that?
You can use the transform.Rotate method to rotate an object around a fixed axis.
The method has various constructors but a simple way to achieve what you want would be using the following depending on the axis you actually want to rotate the object around.
using UnityEngine;
using System.Collections;
public class RotateCylinder : MonoBehaviour
{
// rotation speed in degrees per second.
private float rotationSpeed = 1f;
void Update()
{
// Use one of the following depending on the axis you want to rotate the object, this will depend on how your object is transformed.
// Rotate around X Axis
transform.Rotate(Vector3.right * rotationSpeed * Time.deltaTime);
// Rotate around Y Axis
transform.Rotate(Vector3.up * rotationSpeed * Time.deltaTime);
// Rotate around Z Axis
transform.Rotate(Vector3.forward * rotationSpeed * Time.deltaTime);
}
}
Well, it was rather hard to rotate GameObject ONLY in one axis, nothing worked correctly, adding values to another axis, even RotateAround or Rotate, but...
Vector3 v = transform.localRotation.eulerAngles;
transform.localRotation = Quaternion.Euler(v.x + dx, v.y + dy, v.z + dz);
dx, dy, dz - how much you want to change value in degrees.

Categories