Camera Rotate with Player Unity 3D - c#

I have a ball that move forward and bounce and rotate, and I want the camera to follow it and rotate with it so the camera always look at the ball from behind. So I made the script bellow but the camera didn't look at the ball when rotating!
NB: I didn't use camera as a child of the ball because I don't want the camera to bounce.
Camera Script:
public Transform Ball;
private Vector3 Offset;
// Use this for initialization
void Start () {
Offset = transform.position - Ball.transform.position;
}
// Update is called once per frame
void LateUpdate () {
transform.position = new Vector3(Ball.transform.position.x + Offset.x, transform.position.y, Ball.transform.position.z + Offset.z);
transform.rotation = Ball.transform.rotation;
}

[SerializeField]
private Transform target;
[SerializeField]
private Vector3 offsetPosition;
[SerializeField]
private Space offsetPositionSpace = Space.Self;
[SerializeField]
private bool lookAt = true;
private void Update()
{
Refresh();
}
public void Refresh()
{
if(target == null)
{
Debug.LogWarning("Missing target ref !", this);
return;
}
// compute position
if(offsetPositionSpace == Space.Self)
{
transform.position = target.TransformPoint(offsetPosition);
}
else
{
transform.position = target.position + offsetPosition;
}
// compute rotation
if(lookAt)
{
transform.LookAt(target);
}
else
{
transform.rotation = target.rotation;
}
}
The target is your player gameobject

Related

how can I prevent the camera from sliding after it rotates around the player

I am new to game developing, and I am building a game with an orthographic camera,
the camera suppose to be following the player and when I click and drag the mouse it supposes to turn around him.
I managed to make the camera turn around the player, but when I add the code for the mouse drag when I hold the mouse it turns but when I release it slides.
This is my C# code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerFollow : MonoBehaviour {
public Transform PlayerTransform;
private Vector3 _cameraOffset;
[Range(0.01f, 1.0f)]
[SerializeField] float SmoothFactor = 0.5f;
[SerializeField] bool LookAtPlayer = false;
[SerializeField] bool RotateAroundPlayer = true;
[SerializeField] float RotationsSpeed = 5.0f;
// Use this for initialization
void Start () {
_cameraOffset = transform.position - PlayerTransform.position;
}
void LateUpdate () {
if (Input.GetMouseButtonDown(0))
{
RotateAroundPlayer = true;
}
else if (Input.GetMouseButtonUp(0))
{
RotateAroundPlayer = false;
}
if (RotateAroundPlayer)
{
Quaternion camTurnAngle =
Quaternion.AngleAxis(Input.GetAxis("Mouse X") * RotationsSpeed, Vector3.up);
_cameraOffset = camTurnAngle * _cameraOffset;
}
Vector3 newPos = PlayerTransform.position + _cameraOffset;
transform.position = Vector3.Slerp(transform.position, newPos, SmoothFactor);
if (LookAtPlayer || RotateAroundPlayer)
transform.LookAt(PlayerTransform);
}
}

Unity Camera Switching Issue?

Hi everyone I'm doing a cannonball mode where players will have a UI panel that looks like a snipe screen. This camera will follow the enemy while in regular play there is another camera for normal play mode( this one stays in place). However when I switch between the two wherever the cannon camera moves when I exit with "E" it stays in that moved position. Is there any way where I can manually revert the position of the camera back in place?
public class CameraFollow : MonoBehaviour
{
public Transform target;
public float smoothSpeed = 0.125f;
public Vector3 offset;
public GameObject scopeOverlay;
public GameObject Camera;
void FixedUpdate ()
{
if (Input.GetKeyDown ("d"))
{
Camera.SetActive (false);
scopeOverlay.SetActive(true);
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp (transform.position, desiredPosition, smoothSpeed);
transform.position = smoothedPosition;
transform.LookAt (target);
}
if (Input.GetKeyDown ("e"))
{
Camera.SetActive (true);
scopeOverlay.SetActive(false); //To disable it
}
}
}
Save the initial transform values and restore them like so;
private Vector3 initialPosition;
private Quaternion initialRotation;
private void Start ()
{
// Save initial transform values
initialPosition = transform.position;
initialRotation = transform.rotation;
}
void FixedUpdate ()
{
if (Input.GetKeyDown("d"))
{
Camera.SetActive(false);
scopeOverlay.SetActive(true);
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
transform.position = smoothedPosition;
transform.LookAt(target);
}
if (Input.GetKeyDown("e"))
{
// Restore transform values
transform.position = initialPosition;
transform.rotation = initialRotation;
Camera.SetActive(true);
scopeOverlay.SetActive(false); //To disable it
}
}

Pushes the object on the axes

I have a problem that I can not solve. I have an object, and I want when I click somewhere near him to move with some force. something like the picture below.
I'd even want some idea!!!
Help!!!
public float speed;
public GameObject player;
Vector3 target;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
var mouseClick = Input.mousePosition;
mouseClick.z = player.transform.position.z - Camera.main.transform.position.z;
target = Camera.main.ScreenToWorldPoint(mouseClick);
var distanceToTarget = Vector3.Distance(player.transform.position, target);
if (distanceToTarget > 2)
{
target.z = 0;
player.GetComponent<Rigidbody2D>().AddForce(target * speed);
}
else
print("travelling COMPLETE");
}
}
Using the code you provided in your answer...
public float speed;
public GameObject player;
Vector3 directionVector;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
// Input.mousePosition is already in pixel coordinates so the z should already be 0.
Vector3 mouseWorldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
// Now that the mouse is a world position lets set his z to the same as the player
mouseWorldPosition.z = player.transform.position.z;
// Gives us a direction from the mouse to the player. So think of it as Player <- Mouse remove the < and you have the equation
directionVector = player.transform.position - mouseWorldPosition;
}
else
{
directionVector = Vector3.zero;
}
}
// Physics based movement should be done in FixedUpdate
private void FixedUpdate()
{
player.GetComponent<Rigidbody2D>().AddForce(directionVector.normalized * speed);
}

How to bringback an object to its original position after rotation in unity?

I have created a project where a cube is rotated when we touch on it. I want the cube to return back to its original position when the user stops touching the cube. Below I have added the source code of rotating a cube:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(MeshRenderer))]
public class dr : MonoBehaviour
{
#region ROTATE
private float _sensitivity = 1f;
private Vector3 _mouseReference;
private Vector3 _mouseOffset;
private Vector3 _rotation = Vector3.zero;
private bool _isRotating;
#endregion
void Update()
{
if(_isRotating)
{
// offset
_mouseOffset = (Input.mousePosition - _mouseReference); // apply rotation
_rotation.y = -(_mouseOffset.x + _mouseOffset.y) * _sensitivity; // rotate
gameObject.transform.Rotate(_rotation); // store new mouse position
_mouseReference = Input.mousePosition;
}
}
void OnMouseDown()
{
// rotating flag
_isRotating = true;
// store mouse position
_mouseReference = Input.mousePosition;
}
void OnMouseUp()
{
// rotating flag
_isRotating = false;
}
}
edited code:-
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(MeshRenderer))]
public class pt : MonoBehaviour
{
#region ROTATE
private float _sensitivity = 1f;
private Vector3 _mouseReference;
private Vector3 _mouseOffset;
private Vector3 _rotation = Vector3.zero;
private bool _isRotating;
private Quaternion original;
#endregion
void start(){
original = transform.rotation;
}
void Update()
{
if(_isRotating)
{
// offset
_mouseOffset = (Input.mousePosition - _mouseReference); // apply rotation
_rotation.y = -(_mouseOffset.x + _mouseOffset.y) * _sensitivity; // rotate
gameObject.transform.Rotate(_rotation); // store new mouse position
_mouseReference = Input.mousePosition;
}
}
public void OnMouseDown()
{
// rotating flag
_isRotating = true;
// store mouse position
_mouseReference = Input.mousePosition;
}
public void OnMouseUp()
{
// rotating flag
_isRotating = false;
transform.rotation = original;
}
}
"im trying to rotate a 3d model of a sofa and return to its starting rotation.but if i used this code " whenever if i stopped touching the sofa , it turns to **backside of sofa"**
i want it to return to initial rotation.u can see initally this is how the sofa looks like and if i stopped touching it returns to its backside of sofa. i want it to return to its front side again if i stopped rotation
I want the cube to return back to its original position when the user
stopped touching the cube
I can't exactly tell which part of this you are struggling with but you can simply get the position of the GameObject in the Start or Awake function then set the transform.position to that value when OnMouseUp is called.
private Vector3 originalPos;
void Start()
{
//Get the original position
originalPos = transform.position;
}
void OnMouseUp()
{
_isRotating = false;
//Reset GameObject to the original position
transform.position = originalPos;
}
EDIT:
For rotation, it is also the-same thing. Just use Quaternion and transform.rotation instead of Vector3 and transform.position.
private Quaternion originalPos;
void Start()
{
//Get the original rotation
originalPos = transform.rotation;
}
void OnMouseUp()
{
_isRotating = false;
//Reset GameObject to the original rotation
transform.rotation = originalPos;
}
You still have to incorporate that into the original code from your answer. If this is something you can't do then consider watching Unity's scripting tutorial here.

2D Sprite rotating upside down when coming from right of player C#

Creating a wave based 2d game and this is my current ai script. It works fine other than that whenever the enemy is coming from the right of the player the sprite is rotated upside down and I cant figure out how to fix it. Any help would be appreciated.
public class EnemyAI : MonoBehaviour{
public Transform target;
public int moveSpeed;
public int rotationSpeed;
private Transform myTransform;
// Use this for initialization
void Awake()
{
myTransform = transform;
}
void Start()
{
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
}
// Update is called once per frame
void Update()
{
GameObject go = GameObject.FindGameObjectWithTag("Player");
if (go != null && target != null)
{
Vector3 dir = target.position - myTransform.position;
dir.z = 0.0f; // Only needed if objects don't share 'z' value
if (dir != Vector3.zero)
{
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.FromToRotation(Vector3.right, dir), rotationSpeed * Time.deltaTime);
}
else
{
this.enabled = false;
}
//Move Towards Target
myTransform.position += (target.position -
myTransform.position).normalized * moveSpeed * Time.deltaTime;
}
}
}

Categories