I found and edited a java script that moves the camera from pointA -> pointB and back when you use the scroll wheel. But when I make it a child of the player, the camera doesn't move with it. Any ideas why?
This script is used by the camera:
var pointB : Vector3;
function Start () {
var pointA = transform.position;
while (true) {
yield MoveObject(transform, pointA, pointB, 3.0);
yield MoveObject(transform, pointB, pointA, 3.0);
}
}
function MoveObject (thisTransform : Transform, startPos : Vector3, endPos : Vector3, t) {
var i = 0.0;
var rate = 0.1;
while (i < 1.0) {
i += Input.GetAxis("Mouse ScrollWheel") * rate;
thisTransform.position = Vector3.Lerp(startPos, endPos, i);
yield;
i = Mathf.Clamp(i, 0.0, 10.0);
}
}
Related
this is the code
I add force but I want that the force Will be only on the x-axis and not on the y-axis
Collider2D[] objects = Physics2D.OverlapCircleAll(transform.position, radius, Layertohit);
foreach (Collider2D obj in objects)
{
Vector2 dir = obj.transform.position - transform.position;
dir.y = 0;
obj.GetComponent<Rigidbody2D>().AddForce(dir * force);
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, radius);
}
You can freeze the y axis like
foreach (Collider2D obj in objects)
{
Vector2 dir = obj.transform.position - transform.position;
dir.y = 0;
float y=obj.GetComponent<Rigidbody2D>().velocit.y
obj.GetComponent<Rigidbody2D>().AddForce(dir * force);
obj.GetComponent<Rigidbody2D>().velocity=new Vector2(obj.GetComponent<Rigidbody2D>().velocity.x,y)
}
I am making a 3D game but my player can only move on the X and Y axis. I have a player with an attached camera following my mouse, but I only want it to follow up to a max radius distance from Vector3.zero, even if my mouse is beyond those bounds.
I have tried repositioning the player to the max distance on radius every frame it tries to follow the mouse outside its bounds, but this causes camera jitters even in LateUpdate.
void LateUpdate()
{
if (Input.GetMouseButtonDown(0)) {
firstTouchPos = movementCam.ScreenPointToRay(Input.mousePosition);
playerPos = transform.position;
}
if (Input.GetMouseButton(0)) {
Ray currentTouchPos = movementCam.ScreenPointToRay(Input.mousePosition);
Vector2 direction = currentTouchPos.origin - firstTouchPos.origin;
float distance = Vector3.Distance(transform.position, Vector3.zero);
if (distance >= radius) {
targetPosition = direction.normalized * radius;
} else {
targetPosition = playerPos + direction * touchSensitivity;
}
}
transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * followSpeed);
}
I'm thinking there must be a way to clamp the positioning of the player to a radius so that I don't have to "leash" him back by repositioning him through code every frame.
You should try using Vector3.ClampMagnitude().
The solution was to use Clamp Magnitude.
void LateUpdate()
{
if (Input.GetMouseButtonDown(0)) {
firstTouchPos = movementCam.ScreenPointToRay(Input.mousePosition);
playerPos = transform.position;
}
if (Input.GetMouseButton(0)) {
// targetPosition will follow finger movements
Ray currentTouchPos = movementCam.ScreenPointToRay(Input.mousePosition);
Vector2 direction = currentTouchPos.origin - firstTouchPos.origin;
targetPosition = playerPos + direction * touchSensitivity;
}
transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * followSpeed);
transform.position = Vector3.ClampMagnitude(transform.position, radius);
}
I am creating a game with Unity and I have a math problem.
I have a sphere with a radius of 10 and center of (0, 0, 0).
I want the camera to move around that sphere, but I can't find anywhere a way to do what I want to.
I move the camera in the X axis and the Y axis (and therefore get a point outside of the sphere) and I want to set it's Z axis so the camera would be back on the sphere, I am using this equation: r^2 = x^2 + y^2 + z^2 => z^2 = r^2 - x^2 - y^2
But it doesn't work… Please help me
EDIT
This is my code (in c#):
private void OnMouseDrag()
{
var newX = mainCameraTransform.position.x + Input.GetAxis("Mouse X");
var newY = mainCameraTransform.position.y + Input.GetAxis("Mouse Y");
var maxDistance = 10.0f;
newX = Mathf.Clamp(newX, -maxDistance * 0.85f, maxDistance * 0.85f);
newY = Mathf.Clamp(newY, 1.0f * 0.85f, maxDistance * 0.85f);
var newZ = Mathf.Sqrt(Mathf.Abs(maxDistance * maxDistance - newX * newX - newY * newY));
mainCameraTransform.position = new Vector3(newX, newY, newZ);
mainCameraTransform.LookAt(Vector3.zero);
}
As you can see I used Clamp to keep the X and Y less then the radius but it didn't help…
This isn't tested, but it should be pretty close
private void OnMouseDrag(){
Vector3 newPos = mainCameraTransform.position;
newPos += mainCameraTransform.up * Input.GetAxis("Mouse Y");
newPos += mainCameraTransform.right * Input.GetAxis("Mouse X");
newPos = newPos.normalized * 10f;
mainCameraTransform.position = newPos;
mainCameraTransform.LookAt(Vector3.zero, mainCameraTransform.up);
}
You have to limit 2D coordinates by circle border
len = Mathf.Sqrt(newX * newX + newY * newY);
//perhaps you have Len or Hypot function in your Math library
if len > maxDistance then
newX = maxDistance * newX / len
newY = maxDistance * newY / len;
Drag and drop this script on the camera to orbit it around a target using the right mouse button
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OrbitAroundObject : MonoBehaviour {
public Transform target;
public float distance = 10.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;
public float smoothTime = 2f;
public float zoomSpeed = 1;
float rotationYAxis = 0.0f;
float rotationXAxis = 0.0f;
float velocityX = 0.0f;
float velocityY = 0.0f;
// Use this for initialization
void Start() {
Vector3 angles = transform.eulerAngles;
rotationYAxis = angles.y;
rotationXAxis = angles.x;
// Make the rigid body not change rotation
if (GetComponent<Rigidbody>()) {
GetComponent<Rigidbody>().freezeRotation = true;
}
}
void LateUpdate() {
if (target) {
if (Input.GetMouseButton(1)) {
velocityX += xSpeed * Input.GetAxis("Mouse X") * 0.02f;
velocityY += ySpeed * Input.GetAxis("Mouse Y") * 0.02f;
}
//distance -= (Input.mouseScrollDelta.y*Time.deltaTime);
distance = Mathf.Lerp(distance, distance-(Input.mouseScrollDelta.y*zoomSpeed) , Time.deltaTime * smoothTime);
distance = Mathf.Clamp(distance, distanceMin, distanceMax);
rotationYAxis += velocityX;
rotationXAxis -= velocityY;
rotationXAxis = ClampAngle(rotationXAxis, yMinLimit, yMaxLimit);
//Quaternion fromRotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, 0);
Quaternion toRotation = Quaternion.Euler(rotationXAxis, rotationYAxis, 0);
Quaternion rotation = toRotation;
Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
Vector3 position = rotation * negDistance + target.position;
transform.rotation = rotation;
transform.position = position;
velocityX = Mathf.Lerp(velocityX, 0, Time.deltaTime * smoothTime);
velocityY = Mathf.Lerp(velocityY, 0, Time.deltaTime * smoothTime);
}
}
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);
}
}
I need to rotate car along the path, but the code doesn't work correct. It moves as a firework. I guess that the problem is in moving from z to x axis. I dont have enough knowledge to solve this problem. Help!
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public Transform StartPoint;
public Transform[] EndPoints;
public Transform[] AngleWaypoints;
public float MoveSpeed;
private Transform TargetPoint;
//private Transform EndPoint;
private float DistanceToPoint = 0f;
private int RandomValue;
private Transform[] Waypoints;
private int wpIndex = 0;
private Quaternion lookRotation;
private Vector3 direction;
// Use this for initialization
void Start ()
{
RandomValue = Random.Range (1, EndPoints.Length);
int count = 0;
switch (RandomValue) {
case 0:
//Waypoints = StartPoint + EndPoints [RandomValue];
count = 2;
Waypoints = new Transform[count];
Waypoints [0] = StartPoint;
Waypoints [1] = EndPoints[RandomValue];
break;
case 1:
//Waypoints = StartPoint + AngleWaypoints + EndPoints[RandomValue];
count = 2 + AngleWaypoints.Length;
Waypoints = new Transform[count];
Waypoints [0] = StartPoint;
for(int i=0;i<AngleWaypoints.Length;i++){
Waypoints [i + 1] = AngleWaypoints [i];
}
Waypoints [count-1] = EndPoints[RandomValue];
break;
}
TargetPoint = Waypoints [wpIndex];
}
// Update is called once per frame
void Update ()
{
DistanceToPoint = Vector3.Distance (transform.position, TargetPoint.position);
if (DistanceToPoint > 1) {
direction = (TargetPoint.position - transform.position)/2 + transform.position;
Vector3 dir = TargetPoint.position - transform.position;
lookRotation = Quaternion.LookRotation(dir);
transform.rotation = Quaternion.Slerp (transform.rotation, lookRotation, Time.deltaTime);
Vector3 v = direction / DistanceToPoint * MoveSpeed * Time.deltaTime;
transform.Translate (v);
} else {
wpIndex++;
if (wpIndex > Waypoints.Length - 1) {
wpIndex = 0;
Destroy(this.gameObject);
}
TargetPoint = Waypoints[wpIndex];
}
}
}
I used this code sometime ago and it worked
void Update () {
if (this.isMoving){
if(Vector3.Distance(walkDestination, transform.position) > 0.2f){
float step = 0f;
step = this.speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, walkDestination, step);
Vector3 rotationDestination = this.rotateDestination;
Quaternion targetRotation = Quaternion.LookRotation(rotationDestination - transform.position, Vector3.up);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 6.0f);
}else{
//Arrived to destination
}
}
}
Ok im new to javascript and Unity so this is clearly a very noob beginner question.
Basically I have created a script that i place on my camera. Then when i select a model in the game it becomes the target of the camera script and im trying to make the camera smoothly turn to it. below is what im trying
in the update function i use raycast to catch a unit on the mouse click. this becomes the target variable in the script. it sets a bool to true then to follow target in the moveto function. but it only seems to move the camera if i keep the mouse left button pressed down on the unit. Im trying to select a unit then let the camera smoothly rotate to the unit.
Any ideas on this rookie mistake?
#pragma strict
var speed = 5.0;
var freeMovementTurnSpeed = 10.0;
var freeMovementForwardSpeed = 10.0;
var freeMovementVerticalSpeed = 10.0;
var maxHeight = 30;
var minHeight = 2;
var target : Transform;
var distance = 10.0;
var maxDistance = 50;
var minDistance = 10;
var xSpeed = 250.0;
var ySpeed = 120.0;
var yMinLimit = -20;
var yMaxLimit = 80;
private var x = 0.0;
private var y = 0.0;
// The distance in the x-z plane to the target
var followDistance = 30.0;
var maxDistanceDelta = 0.2;
var damping = 3.0;
var followTarget = false;
var smoothRotation ;
function Start () {
var angles = transform.eulerAngles;
x = angles.y;
y = angles.x;
if(target){
transform.LookAt(target);
}
// Make the rigid body not change rotation
if (rigidbody)
rigidbody.freezeRotation = true;
}
function LateUpdate () {
if(target){
if(followTarget){
moveTo();
}
else{
targetSelectedMovement();
}
}
else {
freeMovement();
}
}
function moveTo(){
//transform.LookAt (target);
var currentDistance = Vector3.Distance(transform.position,target.position);
//if (currentDistance<40){
//followTarget = false;
//}
//else{
smoothRotation = Quaternion.LookRotation(target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, smoothRotation, Time.deltaTime * damping);
print(target);
//transform.position = Vector3.MoveTowards(transform.position,target.position,maxDistanceDelta);
//}
}
function freeMovement(){
var zPos = Input.GetAxis("Vertical") * Time.deltaTime * freeMovementForwardSpeed;
var xPos = Input.GetAxis("Horizontal") * Time.deltaTime * freeMovementTurnSpeed;
var strafePos = Input.GetAxis("Strafe")* Time.deltaTime * freeMovementForwardSpeed;
var vertPos = Input.GetAxis("GainVertical")* Time.deltaTime * freeMovementVerticalSpeed;
if (Input.GetButton("Fire2")) {
x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;
y = ClampAngle(y, yMinLimit, yMaxLimit);
var rotation2 = Quaternion.Euler(y, x, 0);
transform.rotation = rotation2;
}
else {
transform.Rotate(0, Input.GetAxis("Horizontal")*freeMovementTurnSpeed*Time.deltaTime, 0,Space.World);
}
if (vertPos > 0 && transform.position.y > maxHeight){
vertPos = 0;
}
else if(vertPos < 0 && transform.position.y < minHeight){
vertPos = 0;
}
print(transform.position.y);
transform.Translate(strafePos,vertPos,zPos);
}
function targetSelectedMovement() {
if(Input.GetKey("a") || Input.GetKey("d") ){
x += (-Input.GetAxis("Horizontal")) * xSpeed * 0.02;
var rotation = Quaternion.Euler(y, x, 0);
var currentDistance = Vector3.Distance(transform.position,target.position);
var position = rotation * Vector3(0.0, 0.0, -currentDistance) + target.position;
transform.rotation = rotation;
transform.position = position;
}
var zPos = Input.GetAxis("Vertical") * Time.deltaTime * speed;
currentDistance = Vector3.Distance(transform.position,target.position);
if(currentDistance < maxDistance && zPos < 0){
transform.Translate(0, 0, zPos);
}
else if(currentDistance > minDistance && zPos > 0){
transform.Translate(0, 0, zPos);
}
if (Input.GetButton("Fire2")) {
x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;
y = ClampAngle(y, yMinLimit, yMaxLimit);
var rotation2 = Quaternion.Euler(y, x, 0);
var currentDistance2 = Vector3.Distance(transform.position,target.position);
var position2 = rotation2 * Vector3(0.0, 0.0, -currentDistance2) + target.position;
transform.rotation = rotation2;
transform.position = position2;
}
}
static function ClampAngle (angle : float, min : float, max : float) {
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
return Mathf.Clamp (angle, min, max);
}
function Update () {
var hit : RaycastHit;
if (Input.GetButton("Fire1")) {
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
// Cast a ray forward from our position for the specified distance
if (Physics.Raycast(ray, hit))
{
// Add a specified force to the Rigidbody component to the other GameObject
if(hit.collider.tag == "Unit"){
print("Selected " + hit.collider.gameObject.name);
target = hit.collider.gameObject.transform;
//transform.LookAt(target);
followTarget = true;
}
else {
target = null;
}
}
}
}
:)
Answer pulled from my comments above:
"I'll have to look when I get on my dev. machine but in the mean time try replacing Input.GetButton("Fire1") with Input.GetButtonDown("Fire1"). Just as a test, because looking at your code nothing jumps out at me. GetButton is true as long as the button is held, in the past I have had issues with it incorrectly triggering just as the mouse moved off an object."