How to control the jump of my RigidbodyFPSController? - unity3d

I want to control the jump of my RigidBodyFPSController ( a Unity5 script) for a survival game.
The problem is that:
I don't know where is the isJumping variable (forExample, type bool) which allow my character can jump. I want to manipulate that variable to change it to false when my character have low stamina.
What is the way to do that?
var size : Vector2 = new Vector2(240, 40);
//Health Variables
var healthPos : Vector2 = new Vector2(20, 20);
var healthBarDisplay : float = 1;
var healthBarEmpty : Texture2D;
var healthBarFull : Texture2D;
//Hunger Variables
var hungerPos : Vector2 = new Vector2(20, 60);
var hungerBarDisplay : float = 1;
var hungerBarEmpty : Texture2D;
var hungerBarFull : Texture2D;
//Thirst Variables
var thirstPos : Vector2 = new Vector2(20, 100);
var thirstBarDisplay : float = 1;
var thirstBarEmpty : Texture2D;
var thirstBarFull : Texture2D;
//Stamina Variables
var staminaPos : Vector2 = new Vector2(20, 140);
var staminaBarDisplay : float = 1;
var staminaBarEmpty : Texture2D;
var staminaBarFull : Texture2D;
//Fall Rate
var healthFallRate : int = 150;
var hungerFallRate : int = 150;
var thirstFallRate : int = 100;
var staminaFallRate : int = 35;
private var chMotor : CharacterMotor;
private var controller : CharacterController;
var canJump : boolean = false;
var jumpTimer : float = 0.7;
function Start()
{
chMotor = GetComponent(CharacterMotor);
controller = GetComponent(CharacterController);
}
function OnGUI()
{
//Health GUI
GUI.BeginGroup(new Rect (healthPos.x, healthPos.y, size.x, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), healthBarEmpty);
GUI.BeginGroup(new Rect (0, 0, size.x * healthBarDisplay, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), healthBarFull);
GUI.EndGroup();
GUI.EndGroup();
//Hunger GUI
GUI.BeginGroup(new Rect (hungerPos.x, hungerPos.y, size.x, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), hungerBarEmpty);
GUI.BeginGroup(new Rect (0, 0, size.x * hungerBarDisplay, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), hungerBarFull);
GUI.EndGroup();
GUI.EndGroup();
//Thirst GUI
GUI.BeginGroup(new Rect (thirstPos.x, thirstPos.y, size.x, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), thirstBarEmpty);
GUI.BeginGroup(new Rect (0, 0, size.x * thirstBarDisplay, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), thirstBarFull);
GUI.EndGroup();
GUI.EndGroup();
//Stamina GUI
GUI.BeginGroup(new Rect (staminaPos.x, staminaPos.y, size.x, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), staminaBarEmpty);
GUI.BeginGroup(new Rect (0, 0, size.x * staminaBarDisplay, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), staminaBarFull);
GUI.EndGroup();
GUI.EndGroup();
}
function Update()
{
//HEALTH CONTROL SECTION
if(hungerBarDisplay <= 0 && (thirstBarDisplay <= 0))
{
healthBarDisplay -= Time.deltaTime / healthFallRate * 2;
}
else
{
if(hungerBarDisplay <= 0 || thirstBarDisplay <= 0)
{
healthBarDisplay -= Time.deltaTime / healthFallRate;
}
}
if(healthBarDisplay <= 0)
{
CharacterDeath();
}
//HUNGER CONTROL SECTION
if(hungerBarDisplay >= 0)
{
hungerBarDisplay -= Time.deltaTime / hungerFallRate;
}
if(hungerBarDisplay <= 0)
{
hungerBarDisplay = 0;
}
if(hungerBarDisplay >= 1)
{
hungerBarDisplay = 1;
}
//THIRST CONTROL SECTION
if(thirstBarDisplay >= 0)
{
thirstBarDisplay -= Time.deltaTime / thirstFallRate;
}
if(thirstBarDisplay <= 0)
{
thirstBarDisplay = 0;
}
if(thirstBarDisplay >= 1)
{
thirstBarDisplay = 1;
}
//STAMINA CONTROL SECTION
if(controller.velocity.magnitude > 0 && Input.GetKey(KeyCode.LeftShift))
{
chMotor.movement.maxForwardSpeed = 10;
chMotor.movement.maxSidewaysSpeed = 10;
staminaBarDisplay -= Time.deltaTime / staminaFallRate;
}
else
{
chMotor.movement.maxForwardSpeed = 6;
chMotor.movement.maxSidewaysSpeed = 6;
staminaBarDisplay += Time.deltaTime / staminaFallRate;
}
//JUMPING SECTION
if(Input.GetKeyDown(KeyCode.Space) && canJump == true)
{
staminaBarDisplay -= 0.2;
Wait();
}
if(canJump == false)
{
jumpTimer -= Time.deltaTime;
chMotor.jumping.enabled = false;
}
if(jumpTimer <= 0)
{
canJump = true;
chMotor.jumping.enabled = true;
jumpTimer = 0.7;
}
//if(staminaBarDisplay <= 0.05)
//{
//canJump = false;
//chMotor.jumping.enabled = false;
//}
//else
//{
//canJump = true;
//chMotor.jumping.enabled = true;
//}
if(staminaBarDisplay >= 1)
{
staminaBarDisplay = 1;
}
if(staminaBarDisplay <= 0)
{
staminaBarDisplay = 0;
canJump = false;
chMotor.jumping.enabled = false;
chMotor.movement.maxForwardSpeed = 6;
chMotor.movement.maxSidewaysSpeed = 6;
}
}
function CharacterDeath()
{
Application.LoadLevel("SIMPLELEVEL");
}
function Wait()
{
yield WaitForSeconds(0.1);
canJump = false;
}
Here is the code. I don't know how to control the features of the class CharacterMotor, because i think that class was replaced by RygidbodyFirstPersonController.

In the standard controller there is no isJumping variable, but what you can do is set JumpForce = 0 instead for the same effect.
Or you can easily add code for this, in RigidbodyFirstPersonController.cs add some bool value isJumping, and then in Update function make sure to set m_Jump = true only if isJumping is true.

There is a section named JUMPING SECTION. That code controls the jump function. If you want to make some changes, just change this section.

Related

Lerp between point on LineRenderer

Im stuck on how to lerp between points of the linerenderer which are added on runtime. It should animate in order. So IEnumerator should be used i guess.
private void makeLine(Transform finalPoint)
{
if(lastPoints == null)
{
lastPoints = finalPoint;
points.Add(lastPoints);
}
else
{
points.Add(finalPoint);
lr.enabled = true;
SetupLine();
}
}
private void SetupLine()
{
int pointLength = points.Count;
lr.positionCount = pointLength;
for (int i = 0; i < pointLength; i++)
{
lr.SetPosition(i, points[i].position);
// StartCoroutine(AnimateLine());
}
}
I found a code example. But now sure how to implement it so it would fit the code above:
private IEnumerator AnimateLine()
{
//coroutinIsDone = false;
float segmentDuration = animationDuration / points.Count;
for (int i = 0; i < points.Count - 1; i++)
{
float startTime = Time.time;
Vector3 startPosition = points[i].position;
Vector3 endPosition = points[i + 1].position;
Vector3 pos = startPosition;
while (pos != endPosition)
{
float t = (Time.time - startTime) / segmentDuration;
pos = Vector3.Lerp(startPosition, endPosition, t);
for (int j = i + 1; j < points.Count; j++)
lr.SetPosition(j, pos);
yield return null;
}
}
}

GetPixel makes the game slow

I'm creating a cleaning game but in the getpixel line of code makes the game slow or having a delay. I need this line of code to detect the remaining dirt. How can I improve the code? or is there other way to detect remaining dirt?
private void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
if (touch.position != currentPosition || touch.position != prevPosition)
{
SetSinglePixel(touch.position);
prevPosition = touch.position;
}
}
else if (touch.phase == TouchPhase.Moved)
{
if (touch.position != currentPosition || touch.position != prevPosition)
{
currentPosition = touch.position;
Vector2 dif = currentPosition - prevPosition;
float distance = dif.magnitude;
if (distance > 36)
{
float count = distance / 36;
float n = distance / (count + 1);
float ddmo = 36;
for (int i = 0; i <= count; i++)
{
Vector2 gapPoint = Vector2.MoveTowards(prevPosition, currentPosition, ddmo * i);
if (Physics.Raycast(Camera.main.ScreenPointToRay(gapPoint), out RaycastHit hit))
{
gapPositions.Add(hit.textureCoord);
}
}
SetMultiplePixel(gapPositions);
gapPositions.Clear();
}
else
{
SetSinglePixel(currentPosition);
}
prevPosition = touch.position;
}
}
}
}
private void SetMultiplePixel(List<Vector2> givenPoints)
{
foreach (Vector2 pos in givenPoints)
{
SetPixel(pos.x, pos.y);
}
}
private void SetSinglePixel(Vector2 touchPos)
{
if (Physics.Raycast(Camera.main.ScreenPointToRay(touchPos), out RaycastHit hit))
{
SetPixel(hit.textureCoord.x, hit.textureCoord.y);
}
}
public void ResetTexture()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
private void SetPixel(float textureCoordX, float textureCoordY, bool isCheckRemainingTexture = false)
{
int pixelX = (int)(textureCoordX * _templateDirtMask.width);
int pixelY = (int)(textureCoordY * _templateDirtMask.height);
int pixelXOffset = pixelX - (_brush.width / 2);
int pixelYOffset = pixelY - (_brush.height / 2);
for (int x = 0; x < _brush.width; x++)
{
for (int y = 0; y < _brush.height; y++)
{
data = (pixelXOffset + x) + (pixelYOffset + y) * _templateDirtMask.width;
if (data > 0 && data < pixels.Length)
{
pixelDirt = _brush.GetPixel(x, y);// this code makes the game slow
Color pixelDirtMask = _templateDirtMask.GetPixel(pixelXOffset + x, pixelYOffset + y); // this code makes the game slow
float removedAmount = pixelDirtMask.g - (pixelDirtMask.g * pixelDirt.g);
dirtAmount -= removedAmount;
pixels[data] = new Color(0, pixelDirtMask.g * pixelDirt.g, 0);
}
}
}
ApplyTexture();
}

Zooming limit in unity mobile. Perspective Camera

I'm trying to limit the zoom value of my game to a minimum and a maximum but i can't get how to do it!
I've been trying by limiting the Y according to the zoom factor but it does not work properly, because when it reaches the limit, it starts flickering, like it hit an obstacle. I found some things that can solve this problem by using the fieldofview, but I need it to work with the Y limitations!
I also want to add a panning limit, so that the player won't be able to see the end of the map but I didn't get there yet.
Anyways, here is the code i'm using and would appreciate if someone could help!
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
class ScrollAndPinch : MonoBehaviour
{
#if UNITY_IOS || UNITY_ANDROID
public Camera Camera;
public bool Rotate;
protected Plane Plane;
public float scrollSpeed;
public float rotateSpeed;
public float zoomSpeed;
public float zoomMinY;
public float zoomMaxY;
public float camsummer;
Vector3 pos;
private Vector3 velocity = Vector3.zero;
private void Awake()
{
if (Camera == null)
Camera = Camera.main;
Rotate = true;
scrollSpeed = 50f;
rotateSpeed = 50f;
zoomSpeed = 1f;
zoomMinY = 50f;
zoomMaxY = 200f;
camsummer = 0.1f;
pos = new Vector3(0f, 0f, 0f);
}
private void Update()
{
//Update Plane
if (Input.touchCount >= 1)
Plane.SetNormalAndPosition(transform.up, transform.position);
var Delta1 = Vector3.zero;
var Delta2 = Vector3.zero;
//Scroll
if (Input.touchCount == 1)
{
Delta1 = PlanePositionDelta(Input.GetTouch(0));
if (Input.GetTouch(0).phase == TouchPhase.Moved)
Camera.transform.Translate(Delta1 * scrollSpeed * Time.deltaTime, Space.World);
}
//Pinch
if (Input.touchCount == 2)
{
var pos1 = PlanePosition(Input.GetTouch(0).position);
var pos2 = PlanePosition(Input.GetTouch(1).position);
var pos1b = PlanePosition(Input.GetTouch(0).position - Input.GetTouch(0).deltaPosition);
var pos2b = PlanePosition(Input.GetTouch(1).position - Input.GetTouch(1).deltaPosition);
//calc zoom to be done relative to the distance moved between the fingers
var zoom = (Vector3.Distance(pos1, pos2) /
Vector3.Distance(pos1b, pos2b));
//edge case (Bad calculation)
if (zoom == 0 || zoom > 10)
return;
//Move cam amount the mid ray. This is where the zoom is applied
// Vector3 pos = Camera.transform.position;
// pos.y = Mathf.Clamp(pos.y, zoomMinY, zoomMaxY);
// Camera.transform.position = Vector3.Lerp(pos1, Camera.transform.position, (1 / zoom));
// Camera.transform.position = pos;
if (Camera.transform.position.y < zoomMinY | Camera.transform.position.y > zoomMaxY)
{
// Camera.transform.position = pos;
Camera.transform.position = Vector3.SmoothDamp(Camera.transform.position, pos, ref velocity, camsummer);
// Camera.transform.position = Vector3.LerpUnclamped(Camera.transform.position, pos, camsummer);
// for (int i = 0; i < 1000; i++)
// {
// }
}
else if (Camera.transform.position.y >= zoomMinY && Camera.transform.position.y <= zoomMaxY)
{
pos = Camera.transform.position;
Camera.transform.position = Vector3.LerpUnclamped(pos1, Camera.transform.position, (1 / zoom));
//This is where the rotation is applied
if (Rotate && pos2b != pos2)
Camera.transform.RotateAround(pos1, Plane.normal,
Vector3.SignedAngle(pos2 - pos1, pos2b - pos1b, Plane.normal) * rotateSpeed * Time.deltaTime);
}
// pos.y = zoomMinY;
}
// if (Camera.transform.position.y > 200)
// {
// zoomMaxY.y = 200;
// Camera.transform.position = zoomMaxY;
// }
// else if (Camera.transform.position.y < 50)
// {
// zoomMinY.y = 50;
// Camera.transform.position = zoomMinY;
// }
// else if (Camera.transform.position.y >= 50 && Camera.transform.position.y <= 200)
// {
// Camera.transform.position = Vector3.LerpUnclamped(pos1, Camera.transform.position, (1 / zoom));
// }
// Vector3 Cam = Mathf.Clamp(Camera.transform.position.y, zoomMinY.y, zoomMaxY.y);
// if (Camera.transform.position.y > zoomMaxY || Camera.transform.position.y < zoomMinY)
// {
// Vector3 camLimit = Camera.transform.position;
// camLimit.y = Mathf.Clamp(Camera.transform.position.y, zoomMinY, zoomMaxY);
// Camera.transform.position = camLimit;
// // Vector3 camLimit = Camera.transform.position;
// // camLimit = (transform.position.);
// // Camera.transform.position = camLimit;
// }
// else if (Camera.transform.position.y >= zoomMinY && Camera.transform.position.y <= zoomMaxY)
// {
// Camera.transform.position = Vector3.LerpUnclamped(pos1, Camera.transform.position, (1 / zoom));
// }
}
protected Vector3 PlanePositionDelta(Touch touch)
{
//not moved
if (touch.phase != TouchPhase.Moved)
return Vector3.zero;
//delta: How far have we moved from A to B by sliding the finger
var rayBefore = Camera.ScreenPointToRay(touch.position - touch.deltaPosition);
var rayNow = Camera.ScreenPointToRay(touch.position);
if (Plane.Raycast(rayBefore, out var enterBefore) && Plane.Raycast(rayNow, out var enterNow))
return rayBefore.GetPoint(enterBefore) - rayNow.GetPoint(enterNow);
//not on plane
return Vector3.zero;
}
protected Vector3 PlanePosition(Vector2 screenPos)
{
//position
var rayNow = Camera.ScreenPointToRay(screenPos);
if (Plane.Raycast(rayNow, out var enterNow))
return rayNow.GetPoint(enterNow);
return Vector3.zero;
}
private void OnDrawGizmos()
{
Gizmos.DrawLine(transform.position, transform.position + transform.up);
}
#endif
}
And to make it easier to see, this is the part I am struggling to make it work.
if (Camera.transform.position.y < zoomMinY | Camera.transform.position.y > zoomMaxY)
{
Camera.transform.position = Vector3.SmoothDamp(Camera.transform.position, pos, ref velocity, camsummer);
}
else if (Camera.transform.position.y >= zoomMinY && Camera.transform.position.y <= zoomMaxY)
{
pos = Camera.transform.position;
Camera.transform.position = Vector3.LerpUnclamped(pos1, Camera.transform.position, (1 / zoom));
//This is where the rotation is applied
if (Rotate && pos2b != pos2)
Camera.transform.RotateAround(pos1, Plane.normal,
Vector3.SignedAngle(pos2 - pos1, pos2b - pos1b, Plane.normal) * rotateSpeed * Time.deltaTime);
}
Does this happen when the camera gets close to an object?
If so change the near clip plane distance on your camera to.near = 0
That should stop it from not showing the gameobject, if ur camera keeps moving it might cause the flickering because it clips in and out of the near clip plane

MotionEvent getX() and getY(), getRawX() and getRawY() returns wrong value in a TouchImageView

Adding my TouchImageView class below,
public class TouchImageView extends ImageView {
Matrix matrix;
// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
// Remember some things for zooming
PointF last = new PointF();
PointF start = new PointF();
float minScale = -3f;
float maxScale = 3f;
float[] m;
int viewWidth, viewHeight;
static final int CLICK = 3;
float saveScale = 1f;
protected float origWidth, origHeight;
int oldMeasuredWidth, oldMeasuredHeight;
ScaleGestureDetector mScaleDetector;
Context context;
public TouchImageView(Context context) {
super(context);
sharedConstructing(context);
}
public TouchImageView(Context context, AttributeSet attrs) {
super(context, attrs);
sharedConstructing(context);
}
private void sharedConstructing(final Context context) {
super.setClickable(true);
this.context = context;
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
matrix = new Matrix();
m = new float[9];
setImageMatrix(matrix);
setScaleType(ScaleType.MATRIX);
setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
mScaleDetector.onTouchEvent(event);
PointF curr = new PointF(event.getX(), event.getY());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
float x =event.getRawX();
float y = event.getRawY();
Log.d("X & Y",""+x+" "+y);
TouchImageView view = new TouchImageView(context);
ImagePresize imagePresize = new ImagePresize(context);
imagePresize.getXYCordinates(view,x, y);
last.set(curr);
start.set(last);
mode = DRAG;
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) {
float deltaX = curr.x - last.x;
float deltaY = curr.y - last.y;
float fixTransX = getFixDragTrans(deltaX, viewWidth, origWidth * saveScale);
float fixTransY = getFixDragTrans(deltaY, viewHeight, origHeight * saveScale);
matrix.postTranslate(fixTransX, fixTransY);
fixTrans();
last.set(curr.x, curr.y);
}
break;
case MotionEvent.ACTION_UP:
mode = NONE;
int xDiff = (int) Math.abs(curr.x - start.x);
int yDiff = (int) Math.abs(curr.y - start.y);
if (xDiff < CLICK && yDiff < CLICK)
performClick();
break;
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
}
setImageMatrix(matrix);
invalidate();
return true; // indicate event was handled
}
});
}
public void setMaxZoom(float x) {
maxScale = x;
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
mode = ZOOM;
return true;
}
#Override
public boolean onScale(ScaleGestureDetector detector) {
float mScaleFactor = detector.getScaleFactor();
float origScale = saveScale;
saveScale *= mScaleFactor;
if (saveScale > maxScale) {
saveScale = maxScale;
mScaleFactor = maxScale / origScale;
} else if (saveScale < minScale) {
saveScale = minScale;
mScaleFactor = minScale / origScale;
}
if (origWidth * saveScale <= viewWidth || origHeight * saveScale <= viewHeight)
matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2, viewHeight / 2);
else
matrix.postScale(mScaleFactor, mScaleFactor, detector.getFocusX(), detector.getFocusY());
fixTrans();
return true;
}
}
void fixTrans() {
matrix.getValues(m);
float transX = m[Matrix.MTRANS_X];
float transY = m[Matrix.MTRANS_Y];
float fixTransX = getFixTrans(transX, viewWidth, origWidth * saveScale);
float fixTransY = getFixTrans(transY, viewHeight, origHeight * saveScale);
if (fixTransX != 0 || fixTransY != 0)
matrix.postTranslate(fixTransX, fixTransY);
}
float getFixTrans(float trans, float viewSize, float contentSize) {
float minTrans, maxTrans;
if (contentSize <= viewSize) {
minTrans = 0;
maxTrans = viewSize - contentSize;
} else {
minTrans = viewSize - contentSize;
maxTrans = 0;
}
if (trans < minTrans)
return -trans + minTrans;
if (trans > maxTrans)
return -trans + maxTrans;
return 0;
}
float getFixDragTrans(float delta, float viewSize, float contentSize) {
if (contentSize <= viewSize) {
return 0;
}
return delta;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
viewWidth = MeasureSpec.getSize(widthMeasureSpec);
viewHeight = MeasureSpec.getSize(heightMeasureSpec);
//
// Rescales image on rotation
//
if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight
|| viewWidth == 0 || viewHeight == 0)
return;
oldMeasuredHeight = viewHeight;
oldMeasuredWidth = viewWidth;
if (saveScale == 1) {
//Fit to screen.
float scale;
Drawable drawable = getDrawable();
if (drawable == null || drawable.getIntrinsicWidth() == 0 || drawable.getIntrinsicHeight() == 0)
return;
int bmWidth = drawable.getIntrinsicWidth();
int bmHeight = drawable.getIntrinsicHeight();
Log.d("bmSize", "bmWidth: " + bmWidth + " bmHeight : " + bmHeight);
float scaleX = (float) viewWidth / (float) bmWidth;
float scaleY = (float) viewHeight / (float) bmHeight;
scale = Math.min(scaleX, scaleY);
matrix.setScale(scale, scale);
// Center the image
float redundantYSpace = (float) viewHeight - (scale * (float) bmHeight);
float redundantXSpace = (float) viewWidth - (scale * (float) bmWidth);
redundantYSpace /= (float) 2;
redundantXSpace /= (float) 2;
matrix.postTranslate(redundantXSpace, redundantYSpace);
origWidth = viewWidth - 2 * redundantXSpace;
origHeight = viewHeight - 2 * redundantYSpace;
setImageMatrix(matrix);
}
fixTrans();
}
}
getX(), getY(), getRawX(), getRawY() of MotionEvent is returning wrong values. (0,0) coordinate is always shifted to left-bottom from the original.

smooth camera rotation

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."