camera always rotate to 90 degrees - unity3d

so i was writing some codes to make camera follows player, i already set camera rotation to 30 degrees, but when i test it, it always rotate to 90 degrees.
this is my code
public GameObject target;
public float damping = 1;
Vector3 offset;
// Start is called before the first frame update
void Start()
{
offset = target.transform.position - transform.position;
}
// Update is called once per frame
void LateUpdate()
{
float currentAngle = transform.eulerAngles.y;
float desiredAngle = target.transform.eulerAngles.y;
float angle = Mathf.LerpAngle(currentAngle, desiredAngle, Time.deltaTime * damping);
Quaternion rotation = Quaternion.Euler(0, angle, 0);
transform.position = target.transform.position - (rotation * offset);
transform.LookAt(target.transform);
}
how to make camera rotates to 30 degrees instead of 90 degrees?

Related

Unity2D - Enemy shoot at player in a cone shaped pattern

I am trying to set up an enemy that will shoot at the player in a cone shape/shotgun shape. If I set the projectile script to transform.position += transform.right * m_Speed * Time.deltaTime; then the cone shape works as intended, just only to the right and not in the direction of the player. With the current setup (below), the projectile will shoot at the player, but all the bullet prefabs will be on top of each other and all going in the same direction, not in a cone shape.
How can I adjust this so the enemy will shoot at the player but retain the cone shape?
Enemy Script
aimAngle = 60f;
for (int i = 0; i < spreadShot; i++)
{
var shotRotation = gameObject.transform.rotation;
shotRotation *= Quaternion.Euler(0, 0, aimAngle);
GameObject clone = Instantiate(projectile, new Vector2(gameObject.transform.position.x, gameObject.transform.position.y), shotRotation);
aimAngle = aimAngle - 30f;
Vector3 direction = (Vector3)((player.transform.position - transform.position));
direction.Normalize();
clone.GetComponent<Projectile>().Setup(direction);
}
Projectile.cs
[SerializeField] float m_Speed;
Vector3 shootDir;
public void Setup(Vector3 shootDir)
{
this.shootDir = shootDir;
}
private void Update()
{
transform.position += shootDir * m_Speed * Time.deltaTime;
}
Not perfect yet but here is a working solution if anyone else has the same question.
Enemy Script
[SerializeField] public float attackSpread;
[SerializeField] private float startShotTime;
[SerializeField] private float delayShotTime;
[HideInInspector] public int spreadShot;
public void Attack() {
Vector2 targetPosition = target.transform.position - aimIndicator.transform.position;
Vector2 dirTowardsTarget = (targetPosition - (Vector2)transform.position);
transform.right = targetPosition.normalized;
Quaternion newRot;
for (int i = 0; i < spreadShot; i++)
{
float addedOffset = (i - (spreadShot / 2)) * attackSpread;
newRot = Quaternion.Euler(transform.localEulerAngles.x,
transform.localEulerAngles.y,
transform.localEulerAngles.z + addedOffset);
Instantiate(projectile).GetComponent<ButcherProjectile>().SpawnBullet(transform.position, newRot);
}
}
Projectile Script
[SerializeField] private float MovementSpeed = 10;
private Vector2 velocity;
public void SpawnBullet(Vector3 position, Quaternion rotation)
{
transform.position = position;
transform.rotation = rotation;
velocity = transform.right.normalized * MovementSpeed;
}
public void Update()
{
Vector2 nextPosition = (Vector2)transform.position + (velocity * Time.deltaTime);
transform.position = nextPosition;
Destroy(gameObject, 2f);
}
At the moment, your code rotates the bullet itself, not the vector of direction towards player. Shot rotation you computed doesn't affect your direction in any way.
To elaborate, if you rotate an object and just move it by transform.position, you changed its position by exactly how you specified, as if you just changed its x, y or z component by hand. Your rotation change to an object would produce desired results if you used transform.Translate(params) as this operation is dependant on object's current rotation and scale.
Apply your rotation to the direction, it should work just fine :)
More reference on how to do it: https://answers.unity.com/questions/46770/rotate-a-vector3-direction.html

Keep camera from rotating around relative z-axis

I'm trying to create camera movement that mimics the behavior of the unity scene editor where you can perform a spherical rotation around the scene with 2d mouse movement. So far the camera is rotating correctly given x or y movement, but dragging diagonally causes the camera to rotate around its relative z-axis until it gets locked. I cannot force the camera to look at the origin relative to world up because then it cannot rotate upside-down
Here is the script that I've attached to the camera
using UnityEngine;
public class MainCamera : MonoBehaviour
{
Vector2 startingPosition;
Vector2 mousePosition;
Vector3 orthogonalCameraVector;
float degreesPerUnitWidth = 180f / Screen.width;
float degreesPerUnitHeight = 180f / Screen.height;
float cameraRadius = 10;
void Start()
{
transform.position = new Vector3(0, 0, -cameraRadius);
transform.LookAt(Vector3.zero);
orthogonalCameraVector = -Vector3.left;
}
void LateUpdate()
{
if (Input.GetMouseButtonDown(0))
{
mousePosition = Input.mousePosition;
}
if (Input.GetMouseButton(0))
{
var input = new Vector2(Input.mousePosition.x ,Input.mousePosition.y);
startingPosition = mousePosition;
var mouseDelta = startingPosition - input;
var xzDegrees = -mouseDelta.y * degreesPerUnitHeight;
var xzRotation = Quaternion.AngleAxis(xzDegrees, orthogonalCameraVector); // rotate about the relative x-z plane
var yRotation = Quaternion.AngleAxis(-mouseDelta.x * degreesPerUnitWidth, Vector3.up); // rotate about the world y-axis
var rotation = xzRotation * yRotation;
orthogonalCameraVector = rotation * orthogonalCameraVector;
transform.position = rotation * transform.position;
transform.rotation = rotation * transform.rotation;
mousePosition = Input.mousePosition;
}
}
}
I realized the orthogonalCamerVector only needed to be rotated about the y-axis because I wanted to keep it parallel with the xz-plane. I then applied this rotation to the orthogonalCamerVector before rotating the transform so it would always be rotating about a fixed plane so it looks something like this:
var xzDegrees = -mouseDelta.y * degreesPerUnitHeight;
var yRotation = Quaternion.AngleAxis(-mouseDelta.x * degreesPerUnitWidth, Vector3.up); // rotate about the world y-axis
orthogonalCameraVector = yRotation * orthogonalCameraVector;
var xzRotation = Quaternion.AngleAxis(xzDegrees, orthogonalCameraVector); // rotate about the relative x-z plane
var rotation = xzRotation * yRotation;
transform.position = rotation * transform.position;
transform.rotation = rotation * transform.rotation;

Unity 3d main camera LookAt is not rotating on x axis

Am developing a follow target camera, it's working fine but when the vehicle(Target) is on slope, the camera is not rotating to show the full vehicle.
void LateUpdate()
{
if (car1.controlled && Camera.main != null)
{
float speedFactor = Mathf.Clamp01(target.root.GetComponent<Rigidbody>().velocity.magnitude / 20.0f);
if (speedFactor < 0.01f)
speedFactor = 0.01f;
Camera.main.fieldOfView = Mathf.Lerp(40, 65, speedFactor);
float currentDistance = Mathf.Lerp(13.5f, 8.5f, speedFactor);
currentVelocity = currentVelocity.normalized;
Vector3 newTargetPosition = target.position + Vector3.up * height;
Vector3 newPosition = newTargetPosition - ((currentVelocity * currentDistance));
newPosition.y = newTargetPosition.y;
Vector3 targetDirection = newPosition - newTargetPosition;
if (Physics.Raycast(newTargetPosition, targetDirection, out hit, currentDistance, raycastLayers))
newPosition = hit.point;
Camera.main.transform.position = newPosition;
Camera.main.transform.LookAt(newTargetPosition);
}
LookAt is going to set the camera rotation to be looking straight at the newTargetPosition. It doesn't actually moves the camera up, it simply rotates it to look at the vehicule. You should modify your code so the camera moves up when the vehicule goes down a slope and then make it look at the vehicule.

unity camera follow rolling box

i have a cube that rolls with the arrow keys or control pad
up goes up, left turns left, and right turns right, so only the up makes it roll
im trying to get a camera to follow but not really getting anywhere
i found this script cant rember where that im trying to alter
but as i roll the cube forward the camera spins
simple video showing movment
https://imgur.com/a/BfoR1VF
any pointers in the right direction sorry about the pun would be good
simple lookat script
public Transform player;
void Start()
{
}
void Update()
{
Vector3 targetPostion = new Vector3(player.transform.position.x, transform.position.y,player.transform.position.z);
transform.LookAt(targetPostion);
}
and the follow script
// The target we are following
public Transform target;
// The distance in the x-z plane to the target
//So this would be your offset
public float distance = 10.0f;
// the height we want the camera to be above the target
public float height = 5.0f;
// How much we
public float heightDamping = 2.0f;
public float rotationDamping = 3.0f;
void LateUpdate()
{
// Early out if we don't have a target
if (!target) return;
// Calculate the current rotation angles
float wantedRotationAngle = target.eulerAngles.y;
float wantedHeight = target.position.y + height;
float currentRotationAngle = transform.eulerAngles.y;
float currentHeight = transform.position.y;
// Damp the rotation around the y-axis
currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
// Damp the height
currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);
// Convert the angle into a rotation
var currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);
// Set the position of the camera on the x-z plane to:
// distance meters behind the target
transform.position = target.position;
transform.position -= currentRotation * Vector3.forward * distance;
// Set the height of the camera
transform.position = new Vector3(transform.position.x, currentHeight, transform.position.z);
// Always look at the target
Vector3 thetargetPostition = new Vector3(0, target.position.y,0);
transform.LookAt(target.position);
//transform.LookAt(thetargetPostition);

3rd person camera follower in Unity3D

I try to make a 3rd person camera, which follows my player and the camera should rotate, but not the player, if I use the right analog Stick of my controller. I followed this tutorial
My code:
void adjustCameraToPlayer()
{
Quaternion rotation = Quaternion.identity;
if (Input.GetAxis("RightStickX") != 0f)
{
float horizontal = Input.GetAxis("RightStickX") / 100f;
transform.Rotate(0, horizontal, 0);
float desiredAngle = transform.eulerAngles.y;
rotation = Quaternion.Euler(0, desiredAngle, 0);
}
transform.position = player.transform.position-(rotation * offset);
transform.LookAt(player.transform);
}
My problem is that the camera rotates way too fast, I tried to change the dividend of the horizontal value but it did not help.
That's why you always should incorporate deltaTime into transform operations that happen every frame. That way you aren't rotating it at magnitude every single frame, but instead over time. Also you should incorporate a speed variable which can be manipulated in real time, so you can tweak it just how you want:
public float speed = 5f;
void adjustCameraToPlayer()
{
Quaternion rotation = Quaternion.identity;
if (Input.GetAxis("RightStickX") != 0f)
{
float horizontal = Input.GetAxis("RightStickX");
transform.Rotate(Vector3.up * horizontal * speed * Time.deltaTime);
float desiredAngle = transform.eulerAngles.y;
rotation = Quaternion.Euler(0, desiredAngle, 0);
}
transform.position = player.transform.position-(rotation * offset);
transform.LookAt(player.transform);
}