I have a Problem that I just discovered a few days ago and the Problem is that I cant rotate my Object on a Surface with Touch because I only can Rotate it via Mouse and my question is what do I have to add to my Simple Mouse Roatator Script?
Im a beginner with C# and Unity so hopefully somebody could help me here.
Here is the Code:
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
namespace UnityStandardAssets.Utility
{
public class SimpleMouseRotator_E : MonoBehaviour
{
// A mouselook behaviour with constraints which operate relative to
// this gameobject's initial rotation.
// Only rotates around local X and Y.
// Works in local coordinates, so if this object is parented
// to another moving gameobject, its local constraints will
// operate correctly
// (Think: looking out the side window of a car, or a gun turret
// on a moving spaceship with a limited angular range)
// to have no constraints on an axis, set the rotationRange to 360 or greater.
public Vector2 rotationRange = new Vector3(70, 70);
public float rotationSpeed = 10;
public float dampingTime = 0.2f;
public bool autoZeroVerticalOnMobile = true;
public bool autoZeroHorizontalOnMobile = false;
public bool relative = true;
public GameObject reflectionprobe;
public Vector2 startPos;
public Vector2 direction;
public bool directionChosen;
private Vector3 m_TargetAngles;
private Vector3 m_FollowAngles;
private Vector3 m_FollowVelocity;
private Quaternion m_OriginalRotation;
private bool whileDragging;
private void Start()
{
whileDragging = false;
m_OriginalRotation = transform.localRotation;
}
private void Update()
{
// Track a single touch as a direction control.
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
// Handle finger movements based on touch phase.
switch (touch.phase)
{
// Record initial touch position.
case TouchPhase.Began:
startPos = touch.position;
directionChosen = false;
break;
// Determine direction by comparing the current touch position with the initial one.
case TouchPhase.Moved:
direction = touch.position - startPos;
break;
// Report that a direction has been chosen when the finger is lifted.
case TouchPhase.Ended:
directionChosen = true;
break;
}
}
if (directionChosen)
{
// Something that uses the chosen direction...
}
if (whileDragging)
{
// we make initial calculations from the original local rotation
transform.localRotation = m_OriginalRotation;
// read input from mouse or mobile controls
float inputH;
float inputV;
if (relative)
{
inputH = CrossPlatformInputManager.GetAxis("Mouse X");
inputV = CrossPlatformInputManager.GetAxis("Mouse Y");
// wrap values to avoid springing quickly the wrong way from positive to negative
if (m_TargetAngles.y > 180)
{
m_TargetAngles.y -= 360;
m_FollowAngles.y -= 360;
}
if (m_TargetAngles.x > 180)
{
m_TargetAngles.x -= 360;
m_FollowAngles.x -= 360;
}
if (m_TargetAngles.y < -180)
{
m_TargetAngles.y += 360;
m_FollowAngles.y += 360;
}
if (m_TargetAngles.x < -180)
{
m_TargetAngles.x += 360;
m_FollowAngles.x += 360;
}
#if MOBILE_INPUT
// on mobile, sometimes we want input mapped directly to tilt value,
// so it springs back automatically when the look input is released.
if (autoZeroHorizontalOnMobile) {
m_TargetAngles.y = Mathf.Lerp (-rotationRange.y * 0.5f, rotationRange.y * 0.5f, inputH * .5f + .5f);
} else {
m_TargetAngles.y += inputH * rotationSpeed;
}
if (autoZeroVerticalOnMobile) {
m_TargetAngles.x = Mathf.Lerp (-rotationRange.x * 0.5f, rotationRange.x * 0.5f, inputV * .5f + .5f);
} else {
m_TargetAngles.x += inputV * rotationSpeed;
}
#else
// with mouse input, we have direct control with no springback required.
m_TargetAngles.y += inputH * rotationSpeed;
m_TargetAngles.x += inputV * rotationSpeed;
#endif
// clamp values to allowed range
m_TargetAngles.y = Mathf.Clamp(m_TargetAngles.y, -rotationRange.y * 0.5f, rotationRange.y * 0.5f);
m_TargetAngles.x = Mathf.Clamp(m_TargetAngles.x, -rotationRange.x * 1f, rotationRange.x * 0.2f);
}
else
{
inputH = -Input.mousePosition.x;
inputV = -Input.mousePosition.y;
// set values to allowed range
m_TargetAngles.y = Mathf.Lerp(-rotationRange.y * 0.5f, rotationRange.y * 0.5f, inputH / Screen.width);
m_TargetAngles.x = Mathf.Lerp(-rotationRange.x * 1f, rotationRange.x * 1f, inputV / Screen.height);
}
// smoothly interpolate current values to target angles
m_FollowAngles = Vector3.SmoothDamp(m_FollowAngles, m_TargetAngles, ref m_FollowVelocity, dampingTime);
// update the actual gameobject's rotation
transform.localRotation = m_OriginalRotation * Quaternion.Euler(-m_FollowAngles.x, m_FollowAngles.y, 0);
}
}
public void BeginDrag()
{
whileDragging = true;
}
public void EndDrag()
{
whileDragging = false;
}
}
}
Maybe somebody could help me here it would be pretty awesome!
Grettings from Germany
Hmmm, why not try using this?
float rotSpeed = 20;
void OnMouseDrag(){
float rotX = Input.GetAxis("Mouse X") * rotSpeed * Mathf.Deg2Rad;
float rotY = Input.GetAxis("Mouse Y") * rotSpeed * Mathf.Deg2Rad;
transform.RotateAround(Vector3.up, -rotX);
transform.RotateAround(Vector3.right, rotY);
}
A simple way of rotating using touch input :)
Related
I have a problem with my camera movement. I want to limit my camera rotation, but I don't know how to do this. I searched for a solution, but I was not able to find one.
In my current code, my camera rotates rapidly in any direction and I don't know how to implement the Mathf.Clamp correctly.
Here is my code:
public float rightSpeed = 20.0f;
public float leftSpeed = -20.0f;
public float rotationLimit = 0.0f;
void Update()
{
//EdgeScrolling
float edgeSize = 40f;
if (Input.mousePosition.x > Screen.width - edgeSize)
{
//EdgeRight
transform.RotateAround(this.transform.position, Vector3.up, rotationLimit += rightSpeed * Time.deltaTime);
}
if (Input.mousePosition.x < edgeSize)
{
//EdgeLeft
transform.RotateAround(this.transform.position, Vector3.up, rotationLimit -= leftSpeed * Time.deltaTime);
}
rotationLimit = Mathf.Clamp(rotationLimit, 50f, 130f);
}
RotateAround method rotates by an angle. It doesn't assign the angle value you pass it. In this case I would suggest using a different approach. Instead of RotateAround method use the eulerAngles property and assign the rotation values directly.
Example
using UnityEngine;
public class TestScript : MonoBehaviour
{
public float rightSpeed = 20.0f;
public float leftSpeed = -20.0f;
private void Update()
{
float edgeSize = 40f;
if (Input.mousePosition.x > Screen.width - edgeSize)
RotateByY(rightSpeed * Time.deltaTime);
else if (Input.mousePosition.x < edgeSize)
RotateByY(leftSpeed * Time.deltaTime);
}
public void RotateByY(float angle)
{
float newAngle = transform.eulerAngles.y + angle;
transform.eulerAngles = new Vector3(
transform.eulerAngles.x,
Mathf.Clamp(newAngle, 50f, 130f),
transform.eulerAngles.z);
}
}
I can make the camera move the way I want, but I need it to be confined to within the 3D hollow sphere that I created. Currently the player can fly the camera out of the game area.
I've tried parenting the camera to a spherical game object, but the camera still leaves the game area but the sphere stays inside.
This was my attempt at using the BoundingSphere method to keep the camera inside the sphere.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SphericalBoundary : MonoBehaviour
{
public Vector3 pos;
public float r;
void Start()
{
BoundingSphere();
}
private void FixedUpdate()
{
BoundingSphere();
}
public void BoundingSphere()
{
pos = new Vector3(0, 0, 0);
r = (100);
}
}
============================================================================
============================================================================
This is the script that makes the camera fly around. Works perfectly.
using UnityEngine;
using System.Collections;
public class CameraFlight : MonoBehaviour
{
/*
EXTENDED FLYCAM
Desi Quintans (CowfaceGames.com), 17 August 2012.
Based on FlyThrough.js by Slin (http://wiki.unity3d.com/index.php/FlyThrough), 17 May 2011.
LICENSE
Free as in speech, and free as in beer.
FEATURES
WASD/Arrows: Movement
Q: Climb
E: Drop
Shift: Move faster
Control: Move slower
End: Toggle cursor locking to screen (you can also press Ctrl+P to toggle play mode on and off).
*/
public float cameraSensitivity = 90;
public float climbSpeed = 4;
public float normalMoveSpeed = 10;
public float slowMoveFactor = 0.25f;
public float fastMoveFactor = 3;
private float rotationX = 0.0f;
private float rotationY = 0.0f;
void Start()
{
// Screen.lockCursor = true;
}
void Update()
{
rotationX += Input.GetAxis("Mouse X") * cameraSensitivity * Time.deltaTime;
rotationY += Input.GetAxis("Mouse Y") * cameraSensitivity * Time.deltaTime;
rotationY = Mathf.Clamp(rotationY, -90, 90);
transform.localRotation = Quaternion.AngleAxis(rotationX, Vector3.up);
transform.localRotation *= Quaternion.AngleAxis(rotationY, Vector3.left);
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
{
transform.position += transform.forward * (normalMoveSpeed * fastMoveFactor) * Input.GetAxis("Vertical") * Time.deltaTime;
transform.position += transform.right * (normalMoveSpeed * fastMoveFactor) * Input.GetAxis("Horizontal") * Time.deltaTime;
}
else if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
{
transform.position += transform.forward * (normalMoveSpeed * slowMoveFactor) * Input.GetAxis("Vertical") * Time.deltaTime;
transform.position += transform.right * (normalMoveSpeed * slowMoveFactor) * Input.GetAxis("Horizontal") * Time.deltaTime;
}
else
{
transform.position += transform.forward * normalMoveSpeed * Input.GetAxis("Vertical") * Time.deltaTime;
transform.position += transform.right * normalMoveSpeed * Input.GetAxis("Horizontal") * Time.deltaTime;
}
if (Input.GetKey(KeyCode.Q)) { transform.position += transform.up * climbSpeed * Time.deltaTime; }
if (Input.GetKey(KeyCode.E)) { transform.position -= transform.up * climbSpeed * Time.deltaTime; }
//if (Input.GetKeyDown(KeyCode.End))
//{
// Screen.lockCursor = (Screen.lockCursor == false) ? true :][1]
false;
//}
}
}
No errors are showing up. During play the player can fly the camera out of the sphere but I want them confined to the sphere.
I think you must look your camera position on every frame and also check if it's going out of bound of the sphere here is some code which might help you(it is not tested)
public class TestScriptForStackOverflow : MonoBehaviour {
public Transform CameraTrans, SphereTrans;
private float _sphereRadius;
void Start() {
//if we are talking about sphere its localscale.x,y,z values are always equal
_sphereRadius = SphereTrans.localScale.x / 2;
}
void Update() {
if (IsOutsideTheSphere(_sphereRadius, CameraTrans.position, SphereTrans.position)) {
//lets find direction of camera from sphere center
Vector3 direction = (CameraTrans.position - SphereTrans.position).normalized;
//this is bound point for specific direction which is point is on the end of the radius
Vector3 boundPos = SphereTrans.position + direction * _sphereRadius;
//finally assign bound position to camera to stop it to pierce the sphere bounds
CameraTrans.position = boundPos;
}
}
private bool IsOutsideTheSphere(float sphereRadius, Vector3 cameraPosition, Vector3 sphereCenterPosition) {
//distance betweeen cameraPosition and sphereCenterPosition
float distanceBetween = (cameraPosition - sphereCenterPosition).magnitude;
//returns true if distance between sphere center and camera position is longer then sphere radius
return distanceBetween > sphereRadius;
}
If there is something you don't understand ask me in comments
I don't usually post here but it has taken me hours now trying to figure this out and I've searched the net already but couldn't find the answer. I'm wishing someone might be able to assist me here. I'm a newbie and this is the first time I'm trying to combine two types of Third Person Camera Control that follows the Players movement in Unity C#:
Camera Snaps to a pre-defined Position and Rotation as the Player Moves (No Mouse Look)
Mouse Look activates when a Mouse Button is held down and so the Camera rotates according to Mouse movement whether the Player's Position is changing or not
It almost works except that I cannot seem to reset the Mouse Look to its first ever pre-defined setting. After the Player releases the Mouse Button, the code for #1 kicks in and so the Camera seem to go back to its default view. But doing further Mouse Looks, I noticed the Camera always returns to the last position & rotation it was deactivated. I need it to go back to the original pre-defined position & rotation even before the Player activates his first Mouse Look so its not too disorienting for the Player.
I tried several codes but couldn't get it to work so I removed non working lines and just posted those that I think are applicable ones. Please refer to my code below. Would appreciate it if someone can help me. Thanks in advance!
Edit: Updated the code to have two methods of controlling the Camera and added suggested code to reset the currentX & Y values. Comment/uncomment each of the method call to test. But I still have the problem of not being able to smooth out the zooming of the mouse look.
Final Edit: I have again updated the code below, cleaned it up, and included the suggested changes. Code should now be fully working and has no jitters. Thanks for the assistance! :-)
Last Final Edit: Added "Field of View Zooming" by Mouse Wheel and so have completed the code.
using UnityEngine;
using System.Collections;
public class PlayerViewController : MonoBehaviour {
// General Vars
public Transform targetFollow;
private bool lookAround = false;
// For SmoothDampFollow
public Vector3 followDefaultDistance = new Vector3 (0f, 12.0f, -20f);
public float followDistanceDamp = 0.2f;
public Vector3 followVelocity = Vector3.one;
// For Camera Orbit
public float orbitDistance = 20.0f;
public float orbitDamp = 5.0f;
private const float angleMinY = 7.0f;
private const float angleMaxY = 50.0f;
private float currentX = 7.0f;
private float currentY = 50.0f;
// For Zooming Field Of View
public float FOVmin = 50.0f;
public float FOVmax = 100.0f;
public float mouseWheelSpeed = 5.0f;
void Update () {
if (Input.GetMouseButtonDown (1)) {
currentX = transform.eulerAngles.y;
currentY = transform.eulerAngles.x;
}
if (Input.GetMouseButton (1)) {
lookAround = true;
} else {
lookAround = false;
}
ZoomFOV ();
}
void FixedUpdate () {
if (lookAround) {
CameraOrbit ();
} else {
SmoothDampFollow ();
}
}
void ZoomFOV () {
if (Input.GetAxis ("Mouse ScrollWheel") > 0) {
GetComponent<Camera> ().fieldOfView = GetComponent<Camera> ().fieldOfView - mouseWheelSpeed;
if (GetComponent<Camera> ().fieldOfView <= FOVmin) { GetComponent<Camera> ().fieldOfView = FOVmin; }
} else if (Input.GetAxis ("Mouse ScrollWheel") < 0) {
GetComponent<Camera> ().fieldOfView = GetComponent<Camera> ().fieldOfView + mouseWheelSpeed;
if (GetComponent<Camera> ().fieldOfView >= FOVmax) { GetComponent<Camera> ().fieldOfView = FOVmax; }
}
}
void SmoothDampFollow () {
if (!targetFollow) {
return;
} else {
Vector3 wantedPosition = targetFollow.position + (targetFollow.rotation * followDefaultDistance);
transform.position = Vector3.SmoothDamp (transform.position, wantedPosition, ref followVelocity, followDistanceDamp);
transform.LookAt (targetFollow, targetFollow.up);
}
}
void CameraOrbit () {
if (!targetFollow) {
return;
} else {
currentX += Input.GetAxis ("Mouse X");
currentY += Input.GetAxis ("Mouse Y");
currentY = Mathf.Clamp (currentY, angleMinY, angleMaxY);
Vector3 dir = new Vector3 (0, 0, -orbitDistance);
Quaternion rotation = Quaternion.Euler (currentY, currentX, 0);
Vector3 wantedPosition = targetFollow.position + rotation * dir;
transform.position = Vector3.Lerp (transform.position, wantedPosition, Time.deltaTime * orbitDamp);
transform.LookAt (targetFollow.position);
}
}
}
Updated:
Try this
void LateUpdate()
{
if (lookAround)
{
currentX += Input.GetAxisRaw("Mouse X");
currentY += Input.GetAxisRaw("Mouse Y");
currentY = Mathf.Clamp(currentY, angleMinY, angleMaxY);
Vector3 dir = new Vector3(0, 0, -distance);
Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
Vector3 wantedPosition = target.position + rotation * dir;
transform.position = Vector3.Lerp(transform.position, wantedPosition, Time.deltaTime * damping);
camTransform.LookAt(target.position);
}
...
And
void Update()
{
// Here
if (Input.GetMouseButtonDown(1))
{
currentX = transform.eulerAngles.y;
currentY = transform.eulerAngles.x;
}
if (Input.GetMouseButton(1))
{
...
What i've done is i reset the currentX and currentY to their current eulerangle-values on mouse-press in Update(). And i've added a position Lerp to the wanted lookAround position in LateUpdate()
EDIT:
Though I still haven't fixed the smooth zooming of the mouse look when right mouse button is initially held down
Try this change
void CameraOrbit()
{
currentX += Input.GetAxisRaw("Mouse X");
currentY += Input.GetAxisRaw("Mouse Y");
currentY = Mathf.Clamp(currentY, angleMinY, angleMaxY);
Vector3 dir = new Vector3(0, 0, -distance);
Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
// -->
Vector3 wantedPosition = target.position + rotation * dir;
transform.position = Vector3.Lerp(transform.position, wantedPosition, Time.deltaTime * damping);
// <--
camTransform.LookAt(target.position);
}
I'm using this mouseorbit script attached to a camera.
The problem is when i move the camera with the mouse and rotating it so the camera is under the terrain.
I want that when it get to the terrain height then stop don't move down i mean don't get to this view under the character maximum to be in the terrain height..
To stop on terrain height i mean something like that when it's getting to this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseOrbit : MonoBehaviour
{
/* These variables are what tell the camera how its going to function by
* setting the viewing target, collision layers, and other properties
* such as distance and viewing angles */
public Transform viewTarget;
public LayerMask collisionLayers;
public float distance = 6.0f;
public float distanceSpeed = 150.0f;
public float collisionOffset = 0.3f;
public float minDistance = 4.0f;
public float maxDistance = 12.0f;
public float height = 1.5f;
public float horizontalRotationSpeed = 250.0f;
public float verticalRotationSpeed = 150.0f;
public float rotationDampening = 0.75f;
public float minVerticalAngle = -60.0f;
public float maxVerticalAngle = 60.0f;
public bool useRMBToAim = false;
/* These variables are meant to store values given by the script and
* not the user */
private float h, v, smoothDistance;
private Vector3 newPosition;
private Quaternion newRotation, smoothRotation;
private Transform cameraTransform;
/* This is where we initialize our script */
void Start()
{
Initialize();
}
/* This is where we set our private variables, check for null errors,
* and anything else that needs to be called once during startup */
void Initialize()
{
h = this.transform.eulerAngles.x;
v = this.transform.eulerAngles.y;
cameraTransform = this.transform;
smoothDistance = distance;
NullErrorCheck();
}
/* We check for null errors or warnings and notify the user to fix them */
void NullErrorCheck()
{
if (!viewTarget)
{
Debug.LogError("Please make sure to assign a view target!");
Debug.Break();
}
if (collisionLayers == 0)
{
Debug.LogWarning("Make sure to set the collision layers to the layers the camera should collide with!");
}
}
/* This is where we do all our camera updates. This is where the camera
* gets all of its functionality. From setting the position and rotation,
* to adjusting the camera to avoid geometry clipping */
void LateUpdate()
{
if (!viewTarget)
return;
/* We check for right mouse button functionality, set the rotation
* angles, and lock the mouse cursor */
if (!useRMBToAim)
{
/* Check to make sure the game isn't paused and lock the mouse cursor*/
if (Time.timeScale > 0.0f)
Cursor.lockState = CursorLockMode.Locked;
h += Input.GetAxis("Mouse X") * horizontalRotationSpeed * Time.deltaTime;
v -= Input.GetAxis("Mouse Y") * verticalRotationSpeed * Time.deltaTime;
h = ClampAngle(h, -360.0f, 360.0f);
v = ClampAngle(v, minVerticalAngle, maxVerticalAngle);
newRotation = Quaternion.Euler(v, h, 0.0f);
}
else
{
if (Input.GetMouseButton(1))
{
/* Check to make sure the game isn't paused and lock the mouse cursor */
if (Time.timeScale > 0.0f)
Cursor.lockState = CursorLockMode.Locked;
h += Input.GetAxis("Mouse X") * horizontalRotationSpeed * Time.deltaTime;
v -= Input.GetAxis("Mouse Y") * verticalRotationSpeed * Time.deltaTime;
h = ClampAngle(h, -360.0f, 360.0f);
v = ClampAngle(v, minVerticalAngle, maxVerticalAngle);
newRotation = Quaternion.Euler(v, h, 0.0f);
}
else
{
Cursor.lockState = CursorLockMode.Confined;
}
}
/* We set the distance by moving the mouse wheel and use a custom
* growth function as the time value for linear interpolation */
distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel") * 10, minDistance, maxDistance);
smoothDistance = Mathf.Lerp(smoothDistance, distance, TimeSignature(distanceSpeed));
/*We give the rotation some smoothing for a nicer effect */
smoothRotation = Quaternion.Slerp(smoothRotation, newRotation, TimeSignature((1 / rotationDampening) * 100.0f));
newPosition = viewTarget.position;
newPosition += smoothRotation * new Vector3(0.0f, height, -smoothDistance);
/* Calls the function to adjust the camera position to avoid clipping */
CheckSphere();
smoothRotation.eulerAngles = new Vector3(smoothRotation.eulerAngles.x, smoothRotation.eulerAngles.y, 0.0f);
cameraTransform.position = newPosition;
cameraTransform.rotation = smoothRotation;
}
/* This is where the camera checks for a collsion hit within a specified radius,
* and then moves the camera above the location it hit with an offset value */
void CheckSphere()
{
/* Add height to our spherecast origin */
Vector3 tmpVect = viewTarget.position;
tmpVect.y += height;
RaycastHit hit;
/* Get the direction from the camera position to the origin */
Vector3 dir = (newPosition - tmpVect).normalized;
/* Check a radius for collision hits and then set the new position for
* the camera */
if (Physics.SphereCast(tmpVect, 0.3f, dir, out hit, distance, collisionLayers))
{
newPosition = hit.point + (hit.normal * collisionOffset);
}
}
/* Keeps the angles values within their specificed minimum and maximum
* inputs while at the same time putting the values back to 0 if they
* go outside of the 360 degree range */
private float ClampAngle(float angle, float min, float max)
{
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
return Mathf.Clamp(angle, min, max);
}
/* This is our custom logistic growth time signature with speed as input */
private float TimeSignature(float speed)
{
return 1.0f / (1.0f + 80.0f * Mathf.Exp(-speed * 0.02f));
}
}
It looks like the script i grabbed already handles terrain collision... i just need to make sure to set the collision layers on it to include the terrain. But not sure how to do it.
What i tried:
I added now a new layer in the inspector called it Terrain.
Then in the hierarchy on the Terrain i change it's layer to terrain.
Also in the script i selected Terrain. But it's still not working.
In the screenshot the top is the inspector of the camera with the script selected in Collision Layers Terrain.
In the bottom the terrain inspector selected Terrain as :Layer
Many answers to this question.
But here's my take on it since I am fairly certain this solution is interesting compared to all solutions you will find online related to unity 3rd person controllers.
Abstract
In Unity, you could take the usual approach of having an empty object and having that be the parent of the camera, etc... But what people in the industry would typically do is use a mathematical formula called Spherical coordinates.
This, by far, is the best approach for 3rd person controllers from my experience and its the most elegant and beautiful approach. All you need to do after implementing this approach, is shoot a ray from the camera down a meter, and if it detects anything, then change a single value in your spherical coordinates formula which would make the sphere around the player smaller which gives the effect of collision
Implementation
Here's a snippet of code which shows a single function needed to create the spherical coordinates formula.
private Vector3 sphericalCoordinates()
{
float m = distanceFromPlayer;
v = mouseY;
h = mouseX;
x = m * Mathf.Sin(v) * Mathf.Cos(h);
z = m * Mathf.Sin(v) * Mathf.Sin(h);
y = m * Mathf.Cos(v);
Vector3 pos = new Vector3(x, y, z);
return pos;
}
m = magnitude.
You can think of this as the radius from the sphere, this is what you change to give the collision effect.
I later use this snippet to bind the player with the camera in trigger.
[NOTE: very unclean code, I just wanted to show you a basic concept, definitely make it cleaner later]
Vector3 getCamRotWORLD()
{
Vector3 camRotWORLD = new Vector3(0, transform.rotation.eulerAngles.y, 0);
return camRotWORLD;
}
void adjustPlayerRot()
{
if (Input.GetKey(KeyCode.W))
{
player.transform.rotation = Quaternion.Euler(player.transform.rotation.x, getCamRotWORLD().y, player.transform.rotation.z);
player.transform.Translate(0, 0, playerScript.speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.A))
{
player.transform.rotation = Quaternion.Euler(player.transform.rotation.x, getCamRotWORLD().y - 90, player.transform.rotation.z);
player.transform.Translate(0, 0, playerScript.speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.S))
{
player.transform.rotation = Quaternion.Euler(player.transform.rotation.x, getCamRotWORLD().y - 180, player.transform.rotation.z);
player.transform.Translate(0, 0, playerScript.speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D))
{
player.transform.rotation = Quaternion.Euler(player.transform.rotation.x, getCamRotWORLD().y + 90, player.transform.rotation.z);
player.transform.Translate(0, 0, playerScript.speed * Time.deltaTime);
}
}
Here's how my update looks like in case you really would like to snatch the implementation instead of trying to experiment with it yourself.
private void Update()
{
mouseX -= Input.GetAxis("Mouse X") * (sensitivity * Time.deltaTime);
mouseY -= Input.GetAxis("Mouse Y") * (sensitivity * Time.deltaTime);
playerCam.transform.LookAt(player.transform);
playerCam.transform.position = new Vector3(
sphericalCoordinates().x + player.transform.position.x,
sphericalCoordinates().y,
sphericalCoordinates().z + player.transform.position.z
);
}
I am trying to make a 3d viewing simulation in Unity 4 where the user can select an object and move their mouse to rotate around it (360 degrees) I have taken many shots to try get it to work, but I fail each time, any help will be appreciated and if it is written in C# that would be great! (But it doesn't have to)
Thanks in advance!
This is a different and interesting way :) (I use it)
(Here, the cube is the target)
1) Create sphere - Name: "Camera Orbit" - Add material: Transparent (Alpha = 0) - As scale as you want - Rotation: (0,0,0.1f)
2) Add the camera as a "child" to Camera Orbit's surface. Position = (0,"y = camera orbit scale",0)
Rotation = (90,0,0)
3) Create empty GameObject - Name: Input Control.
InputControl.cs:
public class InputControl : MonoBehaviour
{
public GameObject cameraOrbit;
public float rotateSpeed = 8f;
void Update()
{
if (Input.GetMouseButton(0))
{
float h = rotateSpeed * Input.GetAxis("Mouse X");
float v = rotateSpeed * Input.GetAxis("Mouse Y");
if (cameraOrbit.transform.eulerAngles.z + v <= 0.1f || cameraOrbit.transform.eulerAngles.z + v >= 179.9f)
v = 0;
cameraOrbit.transform.eulerAngles = new Vector3(cameraOrbit.transform.eulerAngles.x, cameraOrbit.transform.eulerAngles.y + h, cameraOrbit.transform.eulerAngles.z + v);
}
float scrollFactor = Input.GetAxis("Mouse ScrollWheel");
if (scrollFactor != 0)
{
cameraOrbit.transform.localScale = cameraOrbit.transform.localScale * (1f - scrollFactor);
}
}
}
CameraController.cs:
public class CameraController : MonoBehaviour
{
public Transform cameraOrbit;
public Transform target;
void Start()
{
cameraOrbit.position = target.position;
}
void Update()
{
transform.rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y, 0);
transform.LookAt(target.position);
}
}
4) Add CameraController.cs to Camera.
5) Add InputControl.cs to Input Control.
6) Set public variables in scripts. ("Camera Orbit" and "Target")
That's all. Mouse click and drag: Rotate - Mouse whell: Zoom in-out.
ps. If you want, you can change target as runtime.
The MouseOrbit script do that:
http://wiki.unity3d.com/index.php?title=MouseOrbitImproved#Code_C.23
Just attach this script into your Camera Object, and link the target object in inspector.
-- Use this for the Mouse Press down and drag
-- I modified the code here: http://wiki.unity3d.com/index.php?title=MouseOrbitImproved#Code_C.23
public Transform target;
public float distance = 5.0f;
public float xSpeed = 120.0f;
public float ySpeed = 120.0f;
public float yMinLimit = -20f;
public float yMaxLimit = 80f;
public float distanceMin = .5f;
public float distanceMax = 15f;
private Rigidbody rigidbody;
float x = 0.0f;
float y = 0.0f;
float mouseX = 0f;
float mouseY = 0f;
// Use this for initialization
void Start()
{
Vector3 angles = transform.eulerAngles;
x = angles.y;
y = angles.x;
rigidbody = GetComponent<Rigidbody>();
// Make the rigid body not change rotation
if (rigidbody != null)
{
rigidbody.freezeRotation = true;
}
}
void LateUpdate()
{
if (target)
{
GetMouseButtonDown_XY();
x += mouseX * xSpeed * distance * 0.02f;
y -= mouseY * ySpeed * 0.02f;
y = ClampAngle(y, yMinLimit, yMaxLimit);
Quaternion rotation = Quaternion.Euler(y, x, 0);
distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel") * 5, distanceMin, distanceMax);
RaycastHit hit;
if (Physics.Linecast(target.position, transform.position, out hit))
{
distance -= hit.distance;
}
Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
Vector3 position = rotation * negDistance + target.position;
transform.rotation = rotation;
transform.position = position;
}
}
public static float ClampAngle(float angle, float min, float max)
{
if (angle < -360F)
angle += 360F;
if (angle > 360F)
angle -= 360F;
return Mathf.Clamp(angle, min, max);
}
Vector3 mousePosPrev;
void GetMouseButtonDown_XY()
{
if (Input.GetMouseButtonDown(0))
{
mousePosPrev = Camera.main.ScreenToViewportPoint(Input.mousePosition);
}
if (Input.GetMouseButton(0))
{
Vector3 newMousePos = Camera.main.ScreenToViewportPoint(Input.mousePosition);
if (newMousePos.x < mousePosPrev.x)
{
mouseX = -1;
} else if (newMousePos.x > mousePosPrev.x)
{
mouseX = 1;
} else
{
mouseX = -0;
}
if (newMousePos.y < mousePosPrev.y)
{
mouseY = -1;
}
else if (newMousePos.y > mousePosPrev.y)
{
mouseY = 1;
}
else
{
mouseY = -0;
}
mousePosPrev = Camera.main.ScreenToViewportPoint(Input.mousePosition);
}
}
This is perfect. The only change I made is to add a script to the Camera Orbit:
public class FollowPlayer : MonoBehaviour {
public GameObject player;
private Vector3 playerPos;
// Update is called once per frame
void Update () {
if (this.transform.localScale.x <= 1)
{
this.transform.localScale = new Vector3(1, 1, 1);
}
if (this.transform.localScale.x >= 15)
{
this.transform.localScale = new Vector3(15, 15, 15);
}
playerPos = player.transform.position;
this.transform.position = playerPos;
}
}
Then attach your "player" object to the Input Control, and the input control will go where ever the player does, allowing you to track the player, as well as rotate and mouse wheel zoom. Fancy.
The localScale if statements means you can only zoom in and out so far.
The only problem with this script now is that if you zoom out to 15 and then keep trying to zoom out, the camera bounces. I'm sure that's an easy fix, though, I just haven't put the time in yet.
You don't need the CameraController at all, just set the camera's z rotation to -90.