Unity Health Bar over Enemy Head - c#

I'm having some problems with this so i thought i'd ask here.
I wrote a code that instantiates a health bar (a simple slider) and an enemy. It then sets that enemy (who just spawned) as the target of that health bar and the healthbar updates its position to always stay above the enemys head.
This is the script for the health bar
(canvasRect is the rect transform of the canvas, myRect is the health bars rect transform):
private void Update() {
if(target != null) {
Vector2 targetPosition = Camera.main.WorldToViewportPoint(target.position);
Vector2 screenPosition = new Vector2(((targetPosition.x * canvasRect.sizeDelta.x) - (canvasRect.sizeDelta.x * 0.5f)),
((targetPosition.y * canvasRect.sizeDelta.y) - (canvasRect.sizeDelta.y * 0.5f)));
screenPosition += new Vector2(0f, 15f);
myRect.anchoredPosition = screenPosition;
}
}
The script works great, but there is one problem: as you can see, i'm adding an offset in the y coordinate. This is to place the health bar above the enemy, not inside of it.
The problem comes when i move the camera however. If i zoom in, it rotates a bit (like an RTS camera) which means that the offset is wrong. The further i zoom in, the lower the health bar goes (as the offset of 15f is not enough anymore). And then when i move the camera closer to the enemy, it again pushes the health bar into him.
Is there a way to get the "border" of my enemy in screensize so i can always know what offset to have? Or is there another solution?
Thanks in advance!

The solution is simple. Don't add the offset to the screen position. Instead, add it to the enemy world position (target.position + offset).
In addition to that you can get the bounds of the mesh by using MeshRenderer.bounds.

Related

FlyCamera with collision

How to create collisions for a flying camera in Unity 3d? to prevent the camera from falling into objects on the scene. My camera script snippet:
public class FlyCamera : MonoBehaviour
{
void FixedUpdate()
{
if (!isAlternative)
SetCameraMovement();
}
private void SetCameraMovement()
{
lastMouse = Input.mousePosition - lastMouse;
lastMouse = new Vector3(-lastMouse.y * camSens, lastMouse.x * camSens, 0);
lastMouse = new Vector3(transform.eulerAngles.x + lastMouse.x, transform.eulerAngles.y + lastMouse.y, 0);
if (Input.GetMouseButton(1))
transform.eulerAngles = lastMouse;
lastMouse = Input.mousePosition;
GetBaseInput();
transform.position = Vector3.Lerp(transform.position, NewPosition, Time.deltaTime * movementTime);
}
private void GetBaseInput()
{
Speed = Input.GetKey(KeyCode.LeftShift) ? superSpeed : mainSpeed;
if (Input.GetKey(KeyCode.W))
NewPosition += transform.forward * Speed;
if (Input.GetKey(KeyCode.S))
NewPosition += transform.forward * -Speed;
if (Input.GetKey(KeyCode.A))
NewPosition += transform.right * -Speed;
if (Input.GetKey(KeyCode.D))
NewPosition += transform.right * Speed;
}
}
If you want to achieve a RTS-like flying camera, you can set the camera to a parent dolly-like object and keep it looking at that object:
Object (Camera Dolly) -> this is moved by wasd and is rotated to the desired view angle
Child object: Camera -> only the camera's position.y is ever changed
Then, on a custom script on the dolly in Update(), send a LineCast from the dolly to the camera. When the cast hits a collider (important to use e.g. tags here so it does not collide with anything, like e.g. units) in the world, gradually (over time) reduce the camera's position.y and if nothing is hit, gradually increase it to the desired height. It will not entirely prevent the camera from clipping trough bigger objects but move it so it doesn't stay "inside" a collider. Something like that is also typically used in RPG third person cameras.
Please let me know if more clarification is needed!
Edit: I'd do that only for really big view-blocking objects though, not for the terrain or smaller buildings/units - at least if your goal is more of an RTS or sim game.
Edit2: In a solar system setting, it is a bit more complicated. A few options:
Before translating the camera, do a SphereCast (in the desired (final) movement direction with sphere radius of minimum allowed distance to any object) against all celestial object SphereColliders and set your "NewPosition" to the nearest hitPoint minus the desired minimum allowed distance to a celestial object. Also add some margin here, so the camera doesn't get stuck. This would be a continuous collision detection approach.
Everytime after translating the camera , do a CheckSphere (sphere radius is allowed minium distance to any object) against all celestial objects and as long as there is any hitpoint, lerp the camera position out of it over time. This is a "softer" looking approach, but if you fly very fast, it can still clip into something.
You can savely do both in LateUpdate().
Better put you camera movement in the LateUpdate() as adviced in the docs.
With a rigidbody and a collider properly set for the collision detection. Check docs so that you can detect the collisions properly.
Check that " Notes: Collision events are only sent if one of the colliders also has a non-kinematic rigidbody attached", so your camera could be one gameObject with no rigidbody, so that you can fly free and collide.
I case you might need physics behaviour for yout camera and you want it also to behave as a rigidbody I would set the camera movement with rigidbody.SetPosition instead of with transform.position = new Vector3(), as you need to choose to set the transform in the geometric or the physics world.
Also you would need to uncheck the gravity option not to fall.

How can a make the camera follow a rolling ball from behind?

I am using unity 2018.3.5f1 so a few solutions to this problem don't work.
Starting from the Roll-A-Ball demo project, I want to extend the camera script to follow the player, but also keeping track of the direction of movement. Ex: If the ball starts moving to the side, I need the camera to rotate around the player's axis to position behind him, and then start following him.
I have tried making the camera a child to the ball i'm trying to control and i've tried making a script but it won't follow the ball correctly it keeps rotating the camera as well as the ball (i'm using this bit of code and trying to modify it as it's the only one that works)
here is the code I have at the moment:
using UnityEngine;
using System.Collections;
public class CompleteCameraController : MonoBehaviour
{
public GameObject player; //Public variable to store a reference to the player game object
private Vector3 offset; //Private variable to store the offset distance between the player and camera
// Use this for initialization
void Start()
{
//Calculate and store the offset value by getting the distance between the player's position and camera's position.
offset = transform.position - player.transform.position;
}
// LateUpdate is called after Update each frame
void LateUpdate()
{
// Set the position of the camera's transform to be the same as the player's, but offset by the calculated offset distance.
transform.position = player.transform.position + offset;
}
}
I understand why it is rotating but no reasearch is helping me find out how to lock the camera so it is looking behind the ball at all times
Have you tried adding some restraints to your camera? If it is only supposed to turn to follow the ball, you can freeze the position of 2 axes (x and z), and only let the camera rotate around the y axis of the ball.
You can play around with the restraints on the Inspector, or use GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotationX; in the camera script.
(EDIT) Sorry, this is how you would do it if the gameObject has a rigidbody, but the idea is the same if it doesn't have one.
When you're setting the position or rotation of the camera, think about which components of the position/rotation you actually want to change (x,y,z).
Use offset = new Vector3 (offset.x, offset.y, offset.z)and replace anything that shouldn't change with a constant.
Also, when you made the Camera the child of the ball, you could have set it so that every frame, the Camera updates in such a way that it won't roll with the ball. You could do this by putting code in the update method of the camera that sets the component x, y, or z equal to some constant. Whatever axis the ground plane is on is probably the correct choice.
If you want the same camera angle that the camera should follow while following the ball (similar to Temple Run), then try the below code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class CompleteCameraController : MonoBehaviour
{
public Transform Player;
public float distanceFromObject = 3f;
void Update()
{
Vector3 lookOnObject = Player.position - transform.position;
lookOnObject = Player.position - transform.position;
transform.forward = lookOnObject.normalized;
Vector3 playerLastPosition;
playerLastPosition = Player.position - lookOnObject.normalized * distanceFromObject;
playerLastPosition.y = Player.position.y + distanceFromObject / 2;
transform.position = playerLastPosition;
}
When the ball moves left or right, the camera will follow the same angle as the ball moves towards.

Object Not Looking at Other Object at Right Angle in Unity3D

I'm working on a prototype of a tower defense game and I've encountered a problem with the rotation of a turret. I made it so that every turret must have a rotator part which rotates horizontally and holds the main turret body with the cannon which rotates vertically. I came up with a simple script to this but it only seems to work for the rotator and not for the cannon, at least not the way it should.
Here is the code from the script:
void Update () {
if (target != null) {
Vector3 tempRotatorRotation = rotator.transform.localEulerAngles;
rotator.transform.LookAt (target.transform);
rotator.transform.localEulerAngles = new Vector3 (tempRotatorRotation.x, rotator.transform.localEulerAngles.y, tempRotatorRotation.z);
Vector3 tempCannonRotation = cannon.transform.localEulerAngles;
cannon.transform.LookAt (target.transform);
cannon.transform.localEulerAngles = new Vector3 (cannon.transform.localEulerAngles.x, tempCannonRotation.y, tempCannonRotation.z);
}
}
And here is an image of how this turns out. The rotator is rotated perfectly, but as you can see the cannon is looking down for some reason.
(Blue is the pedestal which doesn't move. Green is rotator. Red is turret body. Light blue is cannon)
The origin of the cannon 3D model is set almost at the start of it.
Here is the screenshot of the canon selected showing it's axis and transform data
forward to unity is the blue line, which in your diagram is facing up. try this
crate empty, attach to turret so it rotates, make sure blue line(z axis) is facing your forward direction, you can do this manualy by rotating. then place your barrel as a child of that object, and point that object at target.
ive had to do this several times with blender models, since blender uses the z axis as its vertical axis not its depth axis like unity.
-turret_test
-turret_test_pedestal
-turret_test_rotater
-turret_test_turret
-AIM(new empty, orient the proper direction then add child)
-turret_test_cannon
Your cannon's barrel points in its forward direction, so all you need to use is cannon.transform.LookAt (target.transform, cannon.transform.up);
void Update () {
if (target != null) {
/* rotator code here */
// Remember which way the top of the cannon faces.
Vector3 cannonUpDirection = cannon.transform.up;
// point the cannon directly at the target
cannon.transform.LookAt (target.transform, cannonUpDirection);
}
}
If the rotator isn't pointing at/above/below the target, then you have to figure out how much to rotate the canon upwards/downwards from the horizontal, then point it in the same direction as the rotator and then do that:
void Update () {
if (target != null) {
/* rotator code here */
// Remember which way the top of the cannon faces.
Vector3 cannonUpDirection = cannon.transform.up;
// point the cannon directly at the target
cannon.transform.LookAt (target.transform, cannonUpDirection);
// Find global direction for looking straight ahead above/below the target
Vector3 sameYDirection = Vector3.Scale(
cannon.transform.forward,
new Vector3(1f,0f,1f)
);
// Convert that to local
Vector3 sameYDirectionLocal = cannon.transform
.InverseTransformDirection(sameYDirection);
// get rotation for moving from looking ahead to looking direct
Quaternion lookTowards = Quaternion.FromToRotation(
sameYDirectionLocal,
Vector3.forward
);
// lookTowards is a locally-vertical rotation from horizontal to the target,
// given some top side of the cannon.
// Clamp lookTowards here if you have a max rotation speed.
// Face cannon in same direction of rotator;
cannon.transform.rotation = Quaternion.LookRotation(
rotator.forward, cannonUpDirection);
// Use lookTowards to look down from that position.
cannon.transform.rotation *= lookTowards;
}
}
Turns out Unity is broken and when I re-imported the model all the axis have changed and instead of the canon turning in the X axis up and down now it was in the Y axis while everything else rotates horizontally in Y.
Also in the calculation I had to add + 90 to both equations. This will make no sense now since it shows both are changing in Y axis but one is rotating horizontally and the other vertically.
if (target != null) {
Vector3 tempRotatorRotation = rotator.transform.localEulerAngles;
rotator.transform.LookAt (target.transform);
rotator.transform.localEulerAngles = new Vector3 (tempRotatorRotation.x, rotator.transform.localEulerAngles.y + 90, tempRotatorRotation.z);
Vector3 tempCanonRotation = canon.transform.localEulerAngles;
canon.transform.LookAt (target.transform);
canon.transform.localEulerAngles = new Vector3 (tempCanonRotation.x, canon.transform.localEulerAngles.y + 90, tempCanonRotation.z);
}

Gyroscope with compass help needed

I need to have a game object point north AND I want to combine this with gyro.attitude input. I have tried, unsuccessfully, to do this in one step. That is, I couldn't make any gyro script, which I found on the net, work with the additional requirement of always pointing north. Trust me, I have tried every script I could find on the subject. I deduced that it's impossible and probably was stupid to think it could be done; at least not this way (i.e. all-in-one). I guess you could say I surmised that you can't do two things at once. Then I thought possibly I could get the same effect by breaking-up the duties. That is, a game object that always points north via the Y axis. Great, got that done like this:
_parentDummyRotationObject.transform.rotation = Quaternion.Slerp(_parentDummyRotationObject.transform.rotation, Quaternion.Euler(0, 360 - Input.compass.trueHeading, 0), Time.deltaTime * 5f);
And with the game object pointing north on the Y, I wanted to add the second game-object, a camera in this case, with rotation using gyro input on the X and Z axis. The reason I have to eliminate the Y axes on the camera is because I get double rotation. With two things rotating at once (i.e. camera and game-object), a 180 degree rotation yielded 360 in the scene. Remember I need the game object to always point north (IRL) based on the device compass. If my device is pointing towards the East, then my game-object would be rotated 90 degrees in the unity scene as it points (rotation) towards the north.
I have read a lot about gyro camera controllers and one thing I see mentioned a lot is you shouldn't try to do this (limit it) on just 1 or 2 axis, when using Quaternions it's impossible when you don't know what you're doing, which I clearly do not.
I have tried all 3 solutions from this solved question: Unity - Gyroscope - Rotation Around One Axis Only and each has failed to rotate my camera on 1 axis to satisfy my rotational needs. Figured I'd try getting 1 axis working before muddying the waters with the 2nd axis. BTW, my requirements are simply that the camera should only rotate on 1 axis (in any orientation) based on the X axis of my device. If I could solve for X, then I thought it'd be great to get Z gyro input to control the camera as well. So far I cannot get the camera controlled on just 1 axis (X). Anyway, here are my findings...
The first solution, which used Input.gyro.rotationRateUnbiased, was totally inaccurate. That is, if I rotated my device around a few times and then put my phone/device down on my desk, the camera would be in a different rotation/location each time. There was no consistency. Here's my code for the first attempt/solution:
<code>
private void Update()
{
Vector3 previousEulerAngles = transform.eulerAngles;
Vector3 gyroInput = Input.gyro.rotationRateUnbiased;
Vector3 targetEulerAngles = previousEulerAngles + gyroInput * Time.deltaTime * Mathf.Rad2Deg;
targetEulerAngles.y = 0.0f;
targetEulerAngles.z = 0.0f;
transform.eulerAngles = targetEulerAngles;
}
</code>
The second solution was very consistent in that I could rotate my device around and then put it down on the desk and the unity camera always ended up in the same location/rotation/state so-to-speak. The problem I had was the camera would rotate on the one axis (X in this case), but it did so when I rotated my device on either the y or x axis. Either type of rotation/movement of my phone caused the unity camera to move on the X. I don't understand why the y rotation of my phone caused the camera to rotate on X. Here is my code for solution #2:
private void Start()
{
Input.gyro.enabled = true;
startEulerAngles = transform.eulerAngles;
startGyroAttitudeToEuler = Input.gyro.attitude.eulerAngles;
}
private void Update()
{
Vector3 deltaEulerAngles = Input.gyro.attitude.eulerAngles - startGyroAttitudeToEuler;
deltaEulerAngles.y = 0.0f;
deltaEulerAngles.z = 0.0f;
transform.eulerAngles = startEulerAngles - deltaEulerAngles;
}
The 3rd solution: I wasn't sure how to complete this last solution, so it never really worked. With the 2 axis zeroed-out, the camera just flipped from facing left to right and back, or top to bottom and back; depending on which axis were commented out. If none of the axis were commented-out (like the original solution) the camera would gyro around on all axis. Here's my code for attempt #3:
private void Start()
{
_upVec = Vector3.zero;
Input.gyro.enabled = true;
startEulerAngles = transform.eulerAngles;
}
private void Update()
{
Vector3 gyroEuler = Input.gyro.attitude.eulerAngles;
phoneDummy.transform.eulerAngles = new Vector3(-1.0f * gyroEuler.x, -1.0f * gyroEuler.y, gyroEuler.z);
_upVec = phoneDummy.transform.InverseTransformDirection(-1f * Vector3.forward);
_upVec.z = 0;
// _upVec.x = 0;
_upVec.y = 0;
transform.LookAt(_upVec);
// transform.eulerAngles = _upVec;
}
Originally I thought it was my skills, but after spending a month on this I'm beginning to think that this is impossible to do. But that just can't be. I know it's a lot to absorb, but it's such a simple concept.
Any ideas?
EDIT: Thought I'd add my hierarchy:
CameraRotator (parent with script) -> MainCamera (child)
CompassRotator (parent) -> Compass (child with script which rotates parent)
I'd do this in the following way:
Camara with default 0, 0, 0 rotation
Screenshot
Object placed at the center of the default position of the camera.
Script for the Camera:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
Camera m_MainCamera;
// Start is called before the first frame update
void Start()
{
// Disable the sleep timeout during gameplay.
// You can re-enable the timeout when menu screens are displayed as necessary.
Screen.sleepTimeout = SleepTimeout.NeverSleep;
// Enable the gyroscope.
if (SystemInfo.supportsGyroscope)
{
Input.gyro.enabled = true;
}
m_MainCamera = Camera.main;
m_MainCamera.enabled = true;
}
// Update is called once per frame
void Update()
{
if (m_MainCamera.enabled)
{
// First - Grab the Gyro's orientation.
Quaternion tAttitude = Input.gyro.attitude;
// The Device uses a 'left-hand' orientation, we need to transform it to 'right-hand'
Quaternion tGyro = new Quaternion(tAttitude.x, tAttitude.y, -tAttitude.z, -tAttitude.w);
// the gyro attitude is tilted towards the floor and upside-down reletive to what we want in unity.
// First Rotate the orientation up 90deg on the X Axis, then 180Deg on the Z to flip it right-side up.
Quaternion tRotation = Quaternion.Euler(-90f, 0, 0) * tGyro;
tRotation = Quaternion.Euler(0, 0, 180f) * tRotation;
// You can now apply this rotation to any unity camera!
m_MainCamera.transform.localRotation = tRotation;
}
}
}
With this script my Object always face SOUTH no matter what.
If you want the object to face NORTH you just have to turn the view 180ยบ on the Y axis as a last rotation:
Quaternion tRotation = Quaternion.Euler(-90f, 0, 0) * tGyro;
tRotation = Quaternion.Euler(0, 0, 180f) * tRotation;
//Face NORTH:
tRotation = Quaternion.Euler(0,180f, 0) * tRotation;
Hope this might help ;)

Rotate around an object to its direction of velocity

(For Unity 5.3.5f1)
Right now I am working on a 3D camera that is orbiting horizontally around the player. The player is a RigidBody rolling sphere. The player can freely rotate the axis horizontally but when there is no input I want the rotation to reset back to the direction of the velocity.
Right now all I need to know is how to situate the camera behind the player's direction of velocity by rotating the camera around the player from its previous rotation.
Here is a crude drawing of what I am looking for:
Currently to update the camera to orbit around the player I use this script on the camera (with comments):
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
public GameObject Player;
//I assume you would use this PlayerRB to find data regarding the movement or velocity of the player.
//public Rigidbody PlayerRB;
private float moveHorizontalCamera;
private Vector3 offset;
// Use this for initialization
void Start ()
{ //the offset of the camera to the player
offset = new Vector3(Player.transform.position.x - transform.position.x, transform.position.y - Player.transform.position.y, transform.position.z - Player.transform.position.z);
}
// Update is called once per frame
void Update ()
{
moveHorizontalCamera = Input.GetAxis("Joy X"); //"Joy X" is my right joystick moving left, none, or right resulting in -1, 0, or 1 respectively
//Copied this part from the web, so I half understand what it does.
offset = Quaternion.AngleAxis(moveHorizontalCamera, Vector3.up) * offset;
transform.position = Player.transform.position + offset;
transform.LookAt(Player.transform.position);
}
}
Any help at all would be great!
I would suggest you use Vector3.RotateTowards (https://docs.unity3d.com/ScriptReference/Vector3.RotateTowards.html)
You take the Vector that is currently pointing from the Player to the camera (transform.position - Player.transform.position) and rotate it towards -Player.GetComponent<Rigidbody>().velocity.normalized * desiredDistance (the vector pointing in the opposite direction of the players velocity with magnitude corresponding the desired distance of the camera to the player). You can then use Vector3.RotateTowards to rotate the camera (smoothly or immediately) around the Player by setting the cameras position accordingly.
Something like:
transform.position = Player.transform.position + Vector3.RotateTowards(transform.position - Player.transform.position, -Player.GetComponent<Rigidbody>().velocity.normalized * desiredDistance, step, .0f);
where step if the angle update in radians. (Note: you should avoid calling GetComponent<Rigidbody>() every Update. You are better off storing it somewhere)
I hope I understood your question correctly and this helps.

Categories

Resources