I want to move main camera slowly from one point to another point when a button is pressed. This button calls the method which has the code to move the camera.
I have tried using the Lerp method but the camera position is changing so fast that when I click on the button camera directly shifting to a new position. I want the camera to move slowly to a new position.
Below is my code, can anyone please help me with this.
=========================================================================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cameramove : MonoBehaviour
{
public GameObject cam;
Vector3 moveToPosition;// This is where the camera will move after the start
float speed = 2f; // this is the speed at which the camera moves
public void move()
{
//Assigning new position to moveTOPosition
moveToPosition = new Vector3(200f, 400f, -220f);
float step = speed * Time.deltaTime;
cam.transform.position = Vector3.Lerp(cam.transform.position, moveToPosition, step);
cam.transform.position = moveToPosition;
}
}
It's easier to use lerp with frames and you need to use it in an Update function. Try using the example from the Unity docs:
public int interpolationFramesCount = 45; // Number of frames to completely interpolate between the 2 positions
int elapsedFrames = 0;
void Update()
{
float interpolationRatio = (float)elapsedFrames / interpolationFramesCount;
Vector3 interpolatedPosition = Vector3.Lerp(Vector3.up, Vector3.forward, interpolationRatio);
elapsedFrames = (elapsedFrames + 1) % (interpolationFramesCount + 1); // reset elapsedFrames to zero after it reached (interpolationFramesCount + 1)
Debug.DrawLine(Vector3.zero, Vector3.up, Color.green);
Debug.DrawLine(Vector3.zero, Vector3.forward, Color.blue);
Debug.DrawLine(Vector3.zero, interpolatedPosition, Color.yellow);
}
Try using smooth damp.
Here is the new code you should try:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cameramove : MonoBehaviour
{
Vector3 matric;
public GameObject cam;
Vector3 moveToPosition;
float speed = 2f;
bool move_ = false;
void Update(){
if(move_){
//Assigning new position to moveTOPosition
moveToPosition = new Vector3(200f, 400f, -220f);
cam.transform.position =
Vector3.SmoothDamp(cam.transform.position,
moveToPosition,
ref matric, speed);
}
}
public void move()
{
move_ = true;
}
}
Related
I haven't used rotation in a while so I can't remember how to do this. I am trying to make a random trajectory for my bullets and I want to add a random rotation but I don't know how to add the rotation. I commented in the script where the rotation should be added. I have tried adding + transform.rotation * Quaternion.Euler(0,rot, 0) but I got the error error CS0019: Operator '+' cannot be applied to operands of type 'Vector3' and 'Quaternion'. What could I add to make this work?
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class Player : MonoBehaviour
{
public GameObject bulletPrefab;
public Camera playerCamera;
private Coroutine hasCourutineRunYet = null;
public int ammo = 300;
public Text Ammmo;
private float xPos;
private float zPos;
private float yPos;
private float rot;
// Update is called once per frame
void Update()
{
Ammmo.text = "Ammo: " + ammo.ToString();
if(Input.GetMouseButtonDown(0))
{
if (hasCourutineRunYet == null)
hasCourutineRunYet = StartCoroutine(BulletShot());
}
}
IEnumerator BulletShot()
{
xPos = Random.Range(-0.3f, 0.3f);
yPos = Random.Range(-0.3f, 0.3f);
zPos = Random.Range(-0.3f, 0.3f);
rot = Random.Range(-10.0f, 10.0f);
GameObject bulletObject = Instantiate(bulletPrefab);
bulletObject.transform.position = playerCamera.transform.position + playerCamera.transform.forward + new Vector3(xPos, yPos, zPos) ; // add rotation here
bulletObject.transform.forward = playerCamera.transform.forward;
yield return new WaitForSeconds(1.0f);
hasCourutineRunYet = null;
ammo--;
}
}
I would look into the transform.rotation.RotateAround function. With this, you can call your bullet's relative forward, and rotate around itself essentially
Code Below:
using UnityEngine;
//Attach this script to a GameObject to rotate around the target position.
public class Example : MonoBehaviour
{
//Assign a GameObject in the Inspector to rotate around
public GameObject target;
void Update()
{
// Spin the object around the target at 20 degrees/second.
transform.RotateAround(target.transform.position, Vector3.up, 20 * Time.deltaTime);
}
}
Here's a URL to the documentation: https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html
Can I make my enemy move just on some suspended blocks? I have a script but my enemy fall of them and doesn't stop when is not any block around . I am bound to put blocks higher just to stop his fall?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
private float latestDirectionChangeTime;
private readonly float directionChangeTime = 3f;
private float characterVelocity = 2f;
private Vector2 movementDirection;
private Vector2 movementPerSecond;
void Start()
{
latestDirectionChangeTime = 0f;
calcuateNewMovementVector();
}
void calcuateNewMovementVector()
{
//create a random direction vector with the magnitude of 1, later multiply it with the velocity of the enemy
movementDirection = new Vector2(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f)).normalized;
movementPerSecond = movementDirection * characterVelocity;
}
void Update()
{
//if the changeTime was reached, calculate a new movement vector
if (Time.time - latestDirectionChangeTime > directionChangeTime)
{
latestDirectionChangeTime = Time.time;
calcuateNewMovementVector();
}
//move enemy:
transform.position = new Vector2(transform.position.x + (movementPerSecond.x * Time.deltaTime),
transform.position.y + (movementPerSecond.y * Time.deltaTime));
}
}
I have looked over the internet for a Camera Script like the one in ROBLOX. But i can't seem to find one. Can anyone help me with this?
Btw i'm using Unity 2017.3
Welcome to Stack Overflow.
I will try to help you out. Please keep in mind though:
Generally questions like this will receive negative feedback as the question isn't specific enough and you haven't provided any attempts or code for us to work with.
People sometimes see this as a "can you do my work for me" scenario.
You are new so I want to take a stab at helping you out regardless.
I hope this helps you and potentially others.
I've included code comments for clarity.
TO USE THIS YOU MUST
create a new script in unity (C#) and attach it to your 'Player' GameObject
edit the script, and paste the below code into the editor
save the script and return to the editor, new settings will appear for the script
modify the settings to your liking and DRAG in the camera to the "The Camera" field
[Edit]
Probably worth mentioning, I also added a pause function to unlock the cursor and return control to the mouse, this can be built upon or removed as needed.
The script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThirdPersonCamera : MonoBehaviour {
//define some constants
private const float LOW_LIMIT = 0.0f;
private const float HIGH_LIMIT = 85.0f;
//these will be available in the editor
public GameObject theCamera;
public float followDistance = 5.0f;
public float mouseSensitivityX = 4.0f;
public float mouseSensitivityY = 2.0f;
public float heightOffset = 0.5f;
//private variables are hidden in editor
private bool isPaused = false;
// Use this for initialization
void Start () {
//place the camera and set the forward vector to match player
theCamera.transform.forward = gameObject.transform.forward;
//hide the cursor and lock the cursor to center
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update () {
//if escape key (default) is pressed, pause the game (feel free to change this)
if (Input.GetButton("Cancel"))
{
//flip the isPaused state, hide/unhide the cursor, flip the lock state
isPaused = !isPaused;
Cursor.visible = !Cursor.visible;
Cursor.lockState = Cursor.lockState == CursorLockMode.Locked ?
CursorLockMode.None : CursorLockMode.Locked;
System.Threading.Thread.Sleep(200);
}
if(!isPaused)
{
//if we are not paused, get the mouse movement and adjust the camera
//position and rotation to reflect this movement around player
Vector2 cameraMovement = new Vector2(Input.GetAxis("Mouse X"),Input.GetAxis("Mouse Y"));
//first we place the camera at the position of the player + height offset
theCamera.transform.position = gameObject.transform.position + new Vector3(0,heightOffset,0);
//next we adjust the rotation based on the captured mouse movement
//we clamp the pitch (X angle) of the camera to avoid flipping
//we also adjust the values to account for mouse sensitivity settings
theCamera.transform.eulerAngles = new Vector3(
Mathf.Clamp(theCamera.transform.eulerAngles.x + cameraMovement.y * mouseSensitivityY, LOW_LIMIT, HIGH_LIMIT),
theCamera.transform.eulerAngles.y + cameraMovement.x * mouseSensitivityX, 0);
//then we move out to the desired follow distance
theCamera.transform.position -= theCamera.transform.forward * followDistance;
}
}
}
This may be inactive, but here is one that moves on right click:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerCamera : MonoBehaviour
{
private const float LOW_LIMIT = 0.0f;
private const float HIGH_LIMIT = 85.0f;
public GameObject theCamera;
public float followDistance = 5.0f;
public float mouseSensitivityX = 4.0f;
public float mouseSensitivityY = 2.0f;
public float heightOffset = 0.5f;
void Start()
{
theCamera.transform.forward = gameObject.transform.forward;
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
}
void Update()
{
if (Input.GetMouseButton(1))
{
Vector2 cameraMovement = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
theCamera.transform.position = gameObject.transform.position + new Vector3(0, heightOffset, 0);
theCamera.transform.eulerAngles = new Vector3(
Mathf.Clamp(theCamera.transform.eulerAngles.x + cameraMovement.y * mouseSensitivityY, LOW_LIMIT, HIGH_LIMIT),
theCamera.transform.eulerAngles.y + cameraMovement.x * mouseSensitivityX, 0);
theCamera.transform.position -= theCamera.transform.forward * followDistance;
}
}
}
I am trying to have my object smoothly rotate on the Z axis from 0 to 180, back and forth on every button press.
The Quaternion.Slerp setup i'm using does not smoothly rotate to the target rotation, rather it instantly jumps to a number close to it. After many button presses that call the Quaternion.Slerp, it it finally halfs works in that it goes from 0 to 180, but still instantly and not smoothly.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
public bool movePlayer;
private float maxMoveSpeed;
public float waitToMove;
Rigidbody2D thisRigidbody;
//SCOOP variables
private GameObject scoop;
private GameObject scoopRotation;
Quaternion currentScoopRotation;
public Quaternion targetScoopRotation;
Quaternion lastScoopRotation;
public float scoopRotateTime;
// Use this for initialization
void Start ()
{
thisRigidbody = gameObject.GetComponent<Rigidbody2D> ();
maxMoveSpeed = moveSpeed;
//SCOOP finders
scoop = GameObject.FindGameObjectWithTag ("Scoop");
currentScoopRotation = scoop.transform.rotation;
}
// Update is called once per frame
void Update ()
{
if(movePlayer)
thisRigidbody.velocity = new Vector2 (moveSpeed, thisRigidbody.velocity.y);
//Rotates SCOOP using Quaternions + Spacebar
if (Input.GetKeyDown(KeyCode.Space)) {
lastScoopRotation = currentScoopRotation;
scoop.transform.transform.rotation = Quaternion.Lerp (currentScoopRotation, targetScoopRotation, scoopRotateTime * Time.time);
currentScoopRotation = targetScoopRotation;
targetScoopRotation = lastScoopRotation;
changeMoveDirection ();
}
}
void changeMoveDirection()
{
moveSpeed *= -1;
}
IEnumerator changeDirectionCO()
{
//thisRigidbody.velocity = new Vector2 (0f,0f);
//moveSpeed = 0;
yield return new WaitForSeconds (waitToMove);
moveSpeed *= -1;
}
}
I'm using the standard camera2DFollow script that comes with Unity 5. But I have a problem with the position of the camera. I've rotated my main camera and it looks like this now.
You see that my player is on top of the screen instead of the middle.
This is the default script in C# for the people who don't have it.
using System;
using UnityEngine;
namespace UnityStandardAssets._2D
{
public class Camera2DFollow : MonoBehaviour
{
public Transform target;
public float damping = 1;
public float lookAheadFactor = 3;
public float lookAheadReturnSpeed = 0.5f;
public float lookAheadMoveThreshold = 0.1f;
private float m_OffsetZ;
private Vector3 m_LastTargetPosition;
private Vector3 m_CurrentVelocity;
private Vector3 m_LookAheadPos;
// Use this for initialization
private void Start()
{
m_LastTargetPosition = target.position;
m_OffsetZ = (transform.position - target.position).z;
transform.parent = null;
}
// Update is called once per frame
private void Update()
{
// only update lookahead pos if accelerating or changed direction
float xMoveDelta = (target.position - m_LastTargetPosition).x;
bool updateLookAheadTarget = Mathf.Abs(xMoveDelta) > lookAheadMoveThreshold;
if (updateLookAheadTarget)
{
m_LookAheadPos = lookAheadFactor*Vector3.right*Mathf.Sign(xMoveDelta);
}
else
{
m_LookAheadPos = Vector3.MoveTowards(m_LookAheadPos, Vector3.zero, Time.deltaTime*lookAheadReturnSpeed);
}
Vector3 aheadTargetPos = target.position + m_LookAheadPos + Vector3.forward*m_OffsetZ;
Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos, ref m_CurrentVelocity, damping);
transform.position = newPos;
m_LastTargetPosition = target.position;
}
}
}
I want to change the Y to a +3 of the current position. So if my camera is on Y 2 than put it on Y 5. (This makes it so the player is in the middle and not on the top).
Thanks for the help!
You can do this by adding 3 to the camera's position at the end of each frame but I recommend against it.
What I would do, is create an empty object, name it "PlayerCameraCenter" and make the player parent to this object; then place the camera center wherever you want relative to the player, like y = 3, and make the camera follow this object instead of the player.
This way you can easily change the position of the camera, through the editor without fiddling with code.