Camera Shake Effect When Camera Following Player - unity3d

I was working on a 3d game where the camera is continuously following the player object.
Now when a bomb hits the player object I want to play camera shake with blast particle effect.
I have coded this for camera shake:
public IEnumerator PlayCameraShakeAnimation(float duration, float magnitude)
{
Vector3 originalPosition = transform.localPosition;
float elapsedTime = 0f;
while(elapsedTime < duration)
{
float x = Random.Range(-1f, 1f) * magnitude;
float y = Random.Range(-1f, 1f) * magnitude;
transform.localPosition = new Vector3(x, y,originalPosition.z);
elapsedTime += Time.deltaTime;
yield return null;
}
transform.localPosition = originalPosition;
}
Camera Follow is the normal script I have written to follow the player.
Because of Camera Follow script is running, camera shake effect we can't able to show in the screen.
If I turn off Camera Follow script then we can able to see clearly camera shaking otherwise not.
If I turn off Camera Follow script for a small amount of time then I am losing smoothness in following of player because the player position gets updated after the blast. So when I start back following the player, it will get a high jerk in a movement to reach a target position.
Also, the Camera is following the player in position and rotation in both fields. Now provide me some suggestions to achieve the Camera Shake effect while following the player.

This is actually quite simple:
Separate it into two GameObjects:
parentObject
|--Camera
parentObject follows player.
Camera does the shaking in localPosition &rightarrow; relative to parentObject
Result: While parentObject follows the player the Camera is automatically moved along with it. No need to turn anything on and of ;)

Related

Unity / Mirror - Is there a way to keep my camera independent from the player object's prefab after start?

I'm currently trying to create a multiplayer game using mirror!
So far I've been successful in creating a lobby and set up a simple character model with a player locomotion script I've taken and learnt inside out from Sebastian Graves on YouTube (you may know him as the dark souls III tutorial guy)
This player locomotion script uses unity's package 'Input System' and is also dependent on using the camera's .forward and .right directions to determine where the player moves and rotates instead of using forces on the rigidbody. This means you actually need the camera free in the scene and unparented from the player.
Here is my HandleRotation() function for rotating my character (not the camera's rotation function):
private void HandleRotation()
{
// target direction is the way we want our player to rotate and move // setting it to 0
Vector3 targetDirection = Vector3.zero;
targetDirection = cameraManager.cameraTransform.forward * inputHandler.verticalInput;
targetDirection += cameraManager.cameraTransform.right * inputHandler.horizontalInput;
targetDirection.Normalize();
targetDirection.y = 0;
if (targetDirection == Vector3.zero)
{
// keep our rotation facing the way we stopped
targetDirection = transform.forward;
}
// Quaternion's are used to calculate rotations
// Look towards our target direction
Quaternion targetRotation = Quaternion.LookRotation(targetDirection);
// Slerp = rotation between current rotation and target rotation by the speed you want to rotate * constant time regardless of framerates
Quaternion playerRotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
transform.rotation = playerRotation;
}
It's also worth mentioning I'm not using cinemachine however I'm open to learning cinemachine as it may be beneficial in the future.
However, from what I've learnt and managed to find about mirror is that you have to parent the Main Camera under your player object's prefab so that when multiple people load in, multiple camera's are created. This has to happen on a Start() function or similar like OnStartLocalPlayer().
public override void OnStartLocalPlayer()
{
if (mainCam != null)
{
// configure and make camera a child of player
mainCam.orthographic = false;
mainCam.transform.SetParent(cameraPivotTransform);
mainCam.transform.localPosition = new Vector3(0f, 0f, -3f);
mainCam.transform.localEulerAngles = new Vector3(0f, 0f, 0f);
cameraTransform = GetComponentInChildren<Camera>().transform;
defaultPosition = cameraTransform.localPosition.z;
}
}
But of course, that means that the camera is no longer independent to the player and so what ends up happening is the camera rotates when the player rotates.
E.g. if I'm in game and looking to the right of my player model and then press 'w' to walk in the direction the camera is facing, my camera will spin with the player keeping the same rotation while my player spins in order to try and walk in the direction the camera is facing.
What my question here would be: Is there a way to create a system using mirror that doesn't require the camera to be parented to the player object prefab on start, and INSTEAD works by keeping it independent in the scene?
(I understand that using forces on a rigidbody is another method of creating a player locomotion script however I would like to avoid that if possible)
If anybody can help that would be greatly appreciated, Thank You! =]
With the constraint of your camera being attached to the player you will have to adapt the camera logic. What you can do is instantiate a proxy transform for the camera and copy that transforms properties to your camera, globally, every frame. The parent constraint component might do this for you. Then do all your transformations on that proxy.
Camera script with instantiation:
Transform proxy;
void Start(){
proxy = (new GameObject()).transform;
}
void Update(){
//transformations on proxy
transform.position = proxy.position;
transform.rotation = proxy.rotation;
}

On Finger Touch and Drag Rotate 3D Ball - Unity 3D

My 3d ball was moving continuously in the forward direction so I want to give X-rotation for this plus game player was dragging ball horizontally on the screen so for this horizontal movement, I want to give Z-rotation.
To achieve my desire, the result I have made ball parent and child game objects, where parent game object only contains collider and rigidbody and this will do the actual physical movement.
Another side, child game object only contains mesh renderer, this will do desire rotation.
Following image gives you more idea about my structure:
Ball Parent:
Ball Child:
For giving rotation to ball mesh as like parent physics ball, I have written this code:
public class BallMeshRolling : MonoBehaviour
{
private Vector3 ballLastPosition;
void Start ()
{
ballLastPosition = transform.parent.position;
}
void Update ()
{
//implementation-1
//float speed = Vector3.Distance (transform.parent.position, ballLastPosition) * 30f;
//transform.RotateAround (transform.position, Vector3.right, speed);
//implementation-2
//Vector3 differenceInPosition = (transform.parent.position - ballLastPosition).normalized;
//transform.Rotate (differenceInPosition * 10f);
//implementation-3
Vector3 differenceInPosition = (transform.parent.position - ballLastPosition).normalized * 50f;
Quaternion rotation = Quaternion.LookRotation(differenceInPosition);
transform.rotation = rotation;
ballLastPosition = transform.parent.position;
}
}
But none of the above ways working properly, so I expect some other better suggestions from your side.
EDIT: Overall I am trying to achieve something like this:
Catch up - Ketchapp - Highscore 1274
There is a tutorial series from Unity about rolling and moving a 3d ball that can help you to figure out the basics for your problem. Wish it could help.
Roll-a-ball tutorial in Unity Tutorials

Unity Mouselook from any Player Orientation

I am working on a first person game where the character is able to latch on to any flat surface and walk on it (kind of like moon boots). I am having issues with the camera since most implementations of mouse look I have been able to find depend on the player being oriented straight up and down in the world, so as soon as my "flipping" animation (the player orienting to the new surface) has finished, the camera will instantly flip back to straight up and down as defined by the world. What I need is a way to implement mouse look so that it does not reset the rotation after my animation. I am currently using:
transform.Rotate(-Input.getAxis("Mouse Y") turnSpeed Time.deltaTime, Input.getAxis("Mouse X") turnSpeed Time.deltaTime, 0);
in order to perform my mouse look rotations while avoiding the standard method, but this is clearly incorrect since I get some weird rotations when turning the camera horizontally. Is there a better way to implement mouse look so that it works correctly regardless of the orientation of the player?
You can plance camera inside player Transform and add this script to player:
public class MouseLook : MonoBehaviour {
[SerializeField]
Camera Camera;
[Range(10f,50f)]
public float Speed = 30;
void Update () {
transform.rotation = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * speed * Time.deltaTime, transform.rotation * Vector3.up)*transform.rotation;
Camera.transform.rotation = Quaternion.AngleAxis(-Input.GetAxis("Mouse Y") * Speed * Time.deltaTime, Camera.transform.rotation * Vector3.right)* Camera.transform.rotation;
}
}
You add reference to Camera in inspector. You will have to check not to rotate above +/- 90 degrees on camera to avoid over rotating to back. If you will have issue with that I will help you.

Camera Zoom when Player Died and Focus the player position c#

i am developing endless game . when player dies then camera zoom and focus on player position. i try and almost done. To zoom the camera i use orthographicSize and focus to the player i use transform.LookAt() that focus the player position when player dies.but the problem is when camera Zoom the scene then entire scene gets rotate. i have created CameraScript and attached to the maincamera .
[SerializeField]
private Camera gameCam;
[SerializeField]
private Transform[] target;
IEnumerator ZoomIn(){
while (gameCam.orthographicSize > 3) {
yield return new WaitForSeconds (0.01f);
transform.LookAt (target [index]);
gameCam.orthographicSize -= 0.1f;
}
}
public void ZoomCam(){
StartCoroutine (ZoomIn ());
}
Help me to that Script if any mistake..Thanks..
I think it's happening because you're not setting the worldUp parameter when you're calling transform.LookAt(...).
I suggest using the camera's own current up vector as that parameter, i.e.
transform.LookAt (target [index], transform.up);
I hope that helps!
EDIT:
Of course, this would only work if your camera is originally oriented as you intend it to be. Else, you'll have to use the vector you choose as the second parameter there.

In Unity3d using the FPS Controller, how can I keep a constant player speed when auto-walk forward using transform.forward?

Using Unity3d First Person Controller, I want the player to move forward automatically in the direction the camera is looking at. It should behave the same as using the arrow keys, except I keep the arrow up key "pressed". I have this working in the script below, however the player slows down as he rotates the first-person camera away from the 0 degrees on the y-axis. When looking towards the 0 degrees on the y-axis, player speed is normal again.
How can I modify the script below so that the player always moves at a constant speed, no matter the camera rotation?
I set this script on the First Person Controller parent node:
public var head : GameObject;
private var motor : CharacterMotor;
// Use this for initialization
function Awake () {
motor = GetComponent(CharacterMotor);
}
// Update is called once per frame
function Update () {
// Retrieve a forward direction based on camera rotation
var directionVector = transform.forward;
directionVector.y = 0;
directionVector.Normalize();
// Apply the direction to the CharacterMotor
motor.inputMoveDirection = transform.rotation * directionVector;
motor.inputJump = Input.GetButton("Jump");
}
// Require a character controller to be attached to the same game object
#script RequireComponent (CharacterMotor)
#script AddComponentMenu ("Character/FPS Input Controller")
Multiply your movement for Time.deltaTime This time is the time between frames.
Example copy from http://docs.unity3d.com/ScriptReference/Time-deltaTime.html
function Update () {
// Move the object 10 meters per second!
var translation : float = Time.deltaTime * 10;
transform.Translate (0, 0, translation);
}