I have two systems that spawn flying enemies. The first system spawns enemies within the FOV:
distanceFromPlayer = 20;
Ray ray = Camera.main.ScreenPointToRay(new Vector3(UnityEngine.Random.Range((float)leftRange,(float)rightRange), UnityEngine.Random.Range((float)bottomRange,(float)topRange), 0));
screenPosition = ray.GetPoint (distanceFromPlayer);
The second system spawns them randomly but with a max angle between enemy and ground. Look at it as if there was a half sphere with the player as center that has been topped off: the enemy can spawn on the surface of that topped sphere:
float distance = distanceFromPlayer;
float yaw = UnityEngine.Random.Range(0,360);
float pitch = UnityEngine.Random.Range(1,35);
screenPosition = RotationHelper.ConvertYawPitch (Vector3.forward * distance, yaw, pitch);
and
public static class RotationHelper {
public static Vector3 ConvertYawPitch(Vector3 vector, float yaw, float pitch)
{
Quaternion yawRotation = Quaternion.AngleAxis (yaw, Vector3.up);
Vector3 yawedZAxis = yawRotation * Vector3.left;
Quaternion pitchRotation = Quaternion.AngleAxis (pitch, yawedZAxis);
Vector3 yawedVector = yawRotation * vector;
Vector3 position = pitchRotation * yawedVector;
return position;
}
}
Now, I want to have a third system for another type of enemies, which basically combines the two systems. So: I want them to spawn inside the field of view, but not above a certain hight, measured from the ground (or below a certain angle like in system two). So if you look to the sky, it should spawn the enemies below the camera's field of view.
I've tried an approach where I make a dummy camera that moves along with the real camera, but can't look upside, but I have the feeling it affects my performance quite drastically, and it doesn't feel like the most efficient way to do it.
Any help is much appreciated!
I went for an approach where I put an invisible ceiling above the player that follows the player's position. If an enemy would spawn behind this invisible ceiling, I recalculate the spawn point.
I use the same technique to make sure enemies don't spawn beneath the floor or behind objects.
This is probably not the most performance friendly way because chances are quite high that it needs to recalculate, so feel free to share other approaches.
Related
I've been told that Rigidbody.MoveRotation is the best way in Unity 3D to rotate the player between fixed positions while still detecting hits. However, while I can move smoothly from fixed position to position with:
if (Vector3.Distance(player.position, targetPos) > 0.0455f) //FIXES JITTER
{
var direction = targetPos - rb.transform.position;
rb.MovePosition(transform.position + direction.normalized * playerSpeed * Time.fixedDeltaTime);
}
I can't find out how to rotate smoothly between fixed positions. I can rotate to the angle I want instantly using Rigidbody.MoveRotation(Vector3 target);, but I can't seem to find a way to do the above as a rotation.
Note: Vector3.Distance is the only thing stopping jitter. Has anyone got any ideas?
First of all MoveRotation doesn't take a Vector3 but rather a Quaternion.
Then in general your jitter might come from overshooting - you might be moving further than the distance between your player and target actually is.
You can avoid that bit by using Vector3.MoveTowards which prevents any overshooting of the target position like e.g.
Rigidbody rb;
float playerSpeed;
Vector3 targetPos;
// in general ONLY g through the Rigidbody as soon as dealing wit Physics
// do NOT go through transform at all
var currentPosition = rb.position;
// This moves with linear speed towards the target WITHOUT overshooting
// Note: It is recommended to always use "Time.deltaTime". It is correct also during "FixedUpdate"
var newPosition = Vector3.MoveTowards(currentPosition, targetPos, playerSpeed * Time.deltaTime);
rb.MovePosition(newPosition);
// [optionally]
// Note: Vector3 == Vector3 uses approximation with a precision of 1e-5
if(rb.position == targetPos)
{
Debug.Log("Arrived at target!");
}
Then you can simply apply this same concept also to rotation by going through the equivalent Quaternion.RotateTowards basically just the same approach
Rigidbody rb;
float anglePerSecond;
Quaternion targetRotation;
var currentRotation = rb.rotation;
var newRotation = Quaternion.RotateTowards(currentRotation, targetRotation, anglePerSecond * Time.deltaTime);
rb.MoveRotation(newRotation);
// [optionally]
// tests whether dot product is close to 1
if(rb.rotation == targetRotation)
{
Debug.Log("Arrived at rotation!");
}
You can go one step further and use a tweeting library to tween between rotations.
DOTween
With that you can call it like this:
rigidbody.DoRotate(target, 1f) to rotate to target in 1 second.
Or even add callbacks.
rigidbody.DoRotate(target, 1f).OnComplete(//any method or lambda you want)
If at some point you want to cancel the tween yuou can save it on a variable and then call tween.Kill();
So, you want to animate the rotation value over time until it reaches a certain value.
Inside the Update method, you can use the Lerp method to keep rotating the object to a point, but you will never really reach this point if you use Lerp. It will keep rotating forever (always closer to the point).
You can use the following:
private bool rotating = true;
public void Update()
{
if (rotating)
{
Vector3 to = new Vector3(20, 20, 20);
if (Vector3.Distance(transform.eulerAngles, to) > 0.01f)
{
transform.eulerAngles = Vector3.Lerp(transform.rotation.eulerAngles, to, Time.deltaTime);
}
else
{
transform.eulerAngles = to;
rotating = false;
}
}
}
So, if the distance between the current object angle and the desired angle is greater than 0.01f, it jumps right to the desired position and stop executing the Lerp method.
travelTime = 0.0f;
while (Vector3.Distance(Vector2.Lerp(startPos, endPos, travelTime), transform.position) >= maxDistance) {
locationToGo = Vector2.Lerp(startPos, Input.mousePosition, travelTime);
travelTime += 0.1f;
}
// SHOW
// Smoothly move the camera towards that target position
transform.position = Vector3.SmoothDamp(transform.position, locationToGo, ref velocity, smoothTime);
So, this code is meant to use Lerp to return a Vector2 a certain amount of 'steps' towards the mouse pointer. And then give that value to the SmoothDamp to move the square to the pos. But the Lerp is not calculating correctly. Does anyone know what is wrong, or any better working alternatives?
Since I don't really know what exactly you are trying to achieve i'm just gonna guess you want to move a GameObject to the MousePosition every Frame.
You could do it like this (it is out of my head, not compileproof):
GameObject ourGameobject;
Vector3 ourTarget;
void Update()
{
ourGameobject.transform.position = Vector3.lerp(ourGameobject.transform.position, ourTarget, Time.DeltaTime);
}
For faster or lower speed just multiply Time.DeltaTime with sth.
Also Note that Input.MousePosition returns a coordinate on the screen.
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.
What I want to do is to make a kind of 2.5D runner game in Unity, which the character's all three rotation axises are frozen and the position on Z axis is also frozen. I don't know how to make the character moving forward nicely on the seesaw. (I create the seesaw by using HingeJoint.)
I create a struct to detect the CapsuleCollider status by using Physics.Raycast() function and that works fine.
private struct ColliderStatus
{
public bool headed; //colliding up
public bool footed; //colliding down
public bool onPlane; //colliding down && the obstacle colliding does not have slope angle
public bool lefted; //colliding left
public bool righted; //colliding right
public bool inAir; //not colliding anything
}
I've tried these ways:
Add force on Rigidbody to move forward
//To move character rigidbody move forward automatically in runner game
//when the speed is lower than the minimum speed and it's on plane or in air.
if (rigidbody.velocity.x < minForwardSpeed && (colliderStatus.onPlane || colliderStatus.inAir))
{
rigidbody.AddForce(20f * Vector3.right);
}
//Add gravity to player
Vector3 gravityForce = new Vector3(0f, -gravityOnPlayer, 0f);
rigidbody.AddForce(gravityForce);
It doesn't work well because the character continue going up when it's on the seesaw though the seesaw starts to tilt. And there will be a velocity loss when the character fall to ground from a higher plane or after jumping and what it looks like is that the character will stunned for a little moment on the landing point and then begin to accelerate.
Use transform.Translate() to move forward && change the way of adding gravity
//Use transform.Translate() to move forward
//I recognize that by this way, there will be no velocity loss
//when the character falling down to the ground at the landing point
//If I don't use this condition, my character will stuck on the
//right vertical wall
if (!colliderStatus.righted)
{
transform.Translate(new Vector2(minForwardSpeed, 0f) * Time.deltaTime);
}
I don't know why I can't write like this since it will cause the velocity doesn't react correctly:
//Use transform.Translate() to move forward
if (!colliderStatus.righted && rigidbody.velocity.x < minForwardSpeed)
{
transform.Translate(new Vector2(minForwardSpeed, 0f) * Time.deltaTime);
}
To change the way of adding gravity, I use a function SlopeAngleVector() to calculate the slope vector the character is running on.
private Vector3 SlopeAngleVector()
{
Vector3 nextStepPositon = new Vector3(transform.position.x + 0.01f, transform.position.y, 0f);
Ray nextPosRay = new Ray(nextStepPositon, Vector3.down);
Ray nowPosRay = new Ray(transform.position, Vector3.down);
RaycastHit nextPosHit;
RaycastHit nowPosHit;
Vector3 slopeAngle = Vector3.zero;
Physics.Raycast(nowPosRay, out nowPosHit, 5f, obstaclesLayerMask);
if (Physics.Raycast(nextPosRay, out nextPosHit, 5f, obstaclesLayerMask))
{
slopeAngle = new Vector3(nextPosHit.point.x - nowPosHit.point.x, nextPosHit.point.y - nowPosHit.point.y, 0f).normalized;
}
return slopeAngle;
}
Then I add the gravity by calculate the gravity projection on the slope vector:
private void AddGravity()
{
Vector3 gravityForce = new Vector3(0f, -gravityOnPlayer, 0f);
//my character could be collided by the long vertical wall(colliderStatus.righted)
//so I set the condition as "!colliderStatus.footed"
//otherwise, I would use "colliderStatus.inAir"
if (!colliderStatus.footed)
{
gravityForce = new Vector3(0f, -gravityOnPlayer, 0f);
}
else
{
gravityForce = Vector3.Project(Vector3.down * gravityOnPlayer, SlopeAngleVector());
}
rigidbody.AddForce(gravityForce);
}
Now my character can slide down from the seesaw but it will keep going backwards. And it cannot make it through when on the low slope angle seesaw.
How to make a good behavior script for the runner on seesaw?
I'd suggest looking at some of the Unity standard asset character controllers, I believe they take slopes into account for their character movement. It may give you some ideas.
I'd also recommend modifying the way your code calculates the angle of the slope. The raycast hit will give you back a surface normal, you should then be able to use the Vector3.Cross to figure out the angle of the slope.
It'll be something like: Vector3.Cross(normal, (vector that points away from screen)).
You may need to tweak it to get it working correctly but this can give you the slope angle in one raycast. It may also eliminate potential issues of your move to position being just below the see saw.
As a general tip, try not to mix transform and rigidbody stuff together, if you want to move the rigidbody, move the rigidbody directly, not indirectly through the transform.
I'm making a basic 2D space shooter game in unity. I have the movements working fine and the camera follows the player. I've been scratching my head over how to give the camera a slight delay from the player moving to the camera moving to catch up to it without it teleporting. I was told to use a Vector3.Lerp and tried a few things from stackoverflow answers but none seemed to work with the way my code is set up. Any suggestions?
(myTarget is linked to the player)
public class cameraFollower : MonoBehaviour {
public Transform myTarget;
void Update () {
if(myTarget != null){
Vector3 targPos = myTarget.position;
targPos.z = transform.position.z;
transform.position = targPos;
}
}
}
If you linear interpolate (Lerp) you risk that Time.deltaTime * speed > 1 in which case the camera will start to extrapolate. That is, instead of following it will get in front if your target.
An alternative is to use pow in your linear interpolation.
float speed = 2.5f;
float smooth = 1.0f - Mathf.Pow(0.5f, Time.deltaTime * speed);
transform.position = Vector3.Lerp(transform.position, targetPos, smooth);
Mathf.Pow(0.5, time) means that after 1/speed second, half of the distance to the target point will be travelled.
The idea with Lerping camera movement is to gradually and smoothly have the camera make its way to the target position.
The further away the camera is, the bigger the distance it will travel per frame, but the closer the camera is, the distance per frame becomes smaller, making the camera ease into its target position.
As an example, try replacing your transform.position = targPos; line with:
float speed = 2.5f; // Set speed to whatever you'd like
transform.position = Vector3.Lerp(transform.position, targPos, Time.deltaTime * speed);