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

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.

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();
}

Developing a 1010 game in unity but pieces rearrange themselves sometimes

I have a bug in my game that I have spent day and night trying to solve but with no success, so please help if you can. Basicaly I have modified the grid(see picture for clarification) and everything seems to work except when I place the pieces at the corner or the edge pieces it suddenly change shape to fit the grid. I am not that good at describing things so I have taken a few screenshots to illustrate.
When I start the game
When I try to set a piece in the grid but one piece is outside
Piece suddenly change shape, when it shouldn't fit and return to spawnpoint
enter image description here
enter image description here
enter image description here
Here is the code for that is attached to every tetris piece:
public TetrimoPiece[] tetrimoPieces;
public Vector3 originalScale;
public Vector3 originalPos;
public Vector3 originalSpawnPos;
Vector3[] _minAndMaxPoints;
Vector3 _centroid;
public bool isBeingDragged;
public TetrimoSpawnPoint assignedSpawnPoint;
public int originalSortingOrder;
public Color color;
public int SortingOrder {
get {
return tetrimoPieces [0].SortingOrder;
}
set {
foreach (TetrimoPiece piece in tetrimoPieces) {
piece.SortingOrder = value;
}
}
}
void Awake ()
{
tetrimoPieces = GetChildTetrimoPieces ();
originalSortingOrder = SortingOrder;
originalScale = transform.localScale;
originalPos = transform.localPosition;
transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x, 0, 0);
if (tetrimoPieces.Count () > 0) {
List<Transform> tetrimoPiecesTransforms = (from tetrimoPiece in tetrimoPieces
select tetrimoPiece.transform).ToList ();
_minAndMaxPoints = GetMinAndMaxPoints (tetrimoPiecesTransforms);
_centroid = FindCentroid (tetrimoPiecesTransforms);
}
SetTetrimoColor ();
}
void Start ()
{
}
public TetrimoPiece[] GetChildTetrimoPieces ()
{
return GetComponentsInChildren<TetrimoPiece> ();
}
public void SetTetrimoColor(){
foreach (TetrimoPiece piece in tetrimoPieces) {
piece.SetColor(color);
}
}
public void GenerateCollider ()
{
List<Transform> tetrimoPiecesTransforms = new List<Transform> ();
foreach (TetrimoPiece piece in tetrimoPieces) {
tetrimoPiecesTransforms.Add (piece.transform);
}
Vector3[] minAndMaxPoints = GetMinAndMaxPoints (tetrimoPiecesTransforms);
Vector3 minPoint = minAndMaxPoints [0];
Vector3 maxPoint = minAndMaxPoints [1];
BoxCollider2D boxColl = gameObject.AddComponent<BoxCollider2D> ();
boxColl.size = new Vector2 ((maxPoint.x - minPoint.x) + tetrimoPieces [0].GetColliderSize ().x, (maxPoint.y - minPoint.y) + tetrimoPieces [0].GetColliderSize ().x);
}
public void MoveTetrimoPiecesToCenter ()
{
List<Transform> tetrimoPiecesTransforms = new List<Transform> ();
foreach (TetrimoPiece piece in tetrimoPieces) {
tetrimoPiecesTransforms.Add (piece.transform);
}
Vector3 centroid = FindCentroid (tetrimoPiecesTransforms);
foreach (Transform child in tetrimoPiecesTransforms) {
child.position -= centroid;
}
}
public Vector3[] GetMinAndMaxPoints (List<Transform> targets)
{
Vector3 minPoint = targets [0].position;
Vector3 maxPoint = targets [0].position;
for (int i = 1; i < targets.Count; i++) {
Vector3 pos = targets [i].position;
if (pos.x < minPoint.x)
minPoint.x = pos.x;
if (pos.x > maxPoint.x)
maxPoint.x = pos.x;
if (pos.y < minPoint.y)
minPoint.y = pos.y;
if (pos.y > maxPoint.y)
maxPoint.y = pos.y;
if (pos.z < minPoint.z)
minPoint.z = pos.z;
if (pos.z > maxPoint.z)
maxPoint.z = pos.z;
}
Vector3[] minAndMaxPoints = new Vector3[]{ minPoint, maxPoint };
return minAndMaxPoints;
}
//CALCULATING THE MEDIAN POINT BETWEEN ALL TETRIMOS
private Vector3 FindCentroid (List< Transform > targets)
{
Vector3 centroid;
Vector3[] minAndMaxPoints = GetMinAndMaxPoints (targets);
Vector3 minPoint = minAndMaxPoints [0];
Vector3 maxPoint = minAndMaxPoints [1];
centroid = minPoint + 0.5f * (maxPoint - minPoint);
return centroid;
}
public void FollowInput ()
{
Vector3 mouseScreenPos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
mouseScreenPos.z = originalPos.z;
transform.position = mouseScreenPos;
}
public bool CanBeReleasedOverGrid ()
{
bool _canBeReleasedOverGrid = true;
List<GridPiece> gridPiecesToFill = new List<GridPiece> ();
foreach (TetrimoPiece piece in tetrimoPieces) {
piece.SetNearestGridPiece ();
gridPiecesToFill.Add (piece.lastNearestGridPiece);
}
foreach (GridPiece gridPiece in gridPiecesToFill) {
if (gridPiece.isFilled || (TutorialManager.instance.isShowingTutorial && !gridPiece.isTutorialFillable)) {
_canBeReleasedOverGrid = false;
break;
}
}
if (TetrimoPiecesShareSameNearestPiece ()) {
_canBeReleasedOverGrid = false;
}
return _canBeReleasedOverGrid;
}
public bool TetrimoPiecesShareSameNearestPiece ()
{
foreach (TetrimoPiece tetrimoPiece in tetrimoPieces) {
foreach (TetrimoPiece brotherPiece in tetrimoPieces) {
bool isBrother = tetrimoPiece != brotherPiece;
if (isBrother) {
if (tetrimoPiece.lastNearestGridPiece == brotherPiece.lastNearestGridPiece) {
return true;
}
}
}
}
return false;
}
public void FillNearestGridPieces ()
{
foreach (TetrimoPiece tetrimoPiece in tetrimoPieces) {
tetrimoPiece.lastNearestGridPiece.SetFilled (true);
tetrimoPiece.lastNearestGridPiece.SetTetrimoThatFillsMe (this);
}
}
public void PlaceOverGrid ()
{
FillNearestGridPieces ();
if (!TutorialManager.instance.isShowingTutorial) {
ScoreHandler.instance.increaseScore (tetrimoPieces.Count ());
}
DestroyImmediate (gameObject);
}
public void MoveToSpawnPosition ()
{
transform.position = originalSpawnPos;
}
public bool CanFitInGrid ()
{
GridPiece[] gridPieces = Grid.instance.gridPieces.ToArray ();
bool canFitInGrid = false;
Vector3 scaleBeforeCheck = transform.localScale;
Vector3 positionBeforeCheck = transform.position;
foreach (GridPiece gridPiece in gridPieces) {
if (gridPiece != null)
{
transform.localScale = originalScale;
transform.position = gridPiece.transform.position;
transform.position += new Vector3(transform.position.x - tetrimoPieces[0].transform.position.x, transform.position.y - tetrimoPieces[0].transform.position.y, transform.position.z);
if (CanBeReleasedOverGrid())
{
canFitInGrid = true;
break;
}
}
}
transform.position = positionBeforeCheck;
transform.localScale = scaleBeforeCheck;
return canFitInGrid;
}
public void ReturnToSpawnPoint (float timeToReachOriginalPos)
{
if (OnReturnToSpawnPointRoutine == null) {
OnReturnToSpawnPointRoutine = DOOnReturnToSpawnPointRoutine (timeToReachOriginalPos);
StartCoroutine (OnReturnToSpawnPointRoutine);
}
}
public IEnumerator OnReturnToSpawnPointRoutine;
public IEnumerator DOOnReturnToSpawnPointRoutine (float timeToReachOriginalPos, bool animated = true)
{
float timeToReachValues = timeToReachOriginalPos;
float t = 0;
float timePassed = 0;
Vector3 startPos = transform.position;
Vector3 startScale = transform.localScale;
Vector3 targetScale = originalScale * TetrimoSpawner.instance.scaleFactorOnSpawnPoint;
if (!animated) {
t = 1;
}
while (t <= 1) {
if (this == null || isBeingDragged) {
yield break;
}
transform.localScale = Vector3.Lerp (startScale, targetScale, t);
transform.position = Vector3.Lerp (startPos, originalSpawnPos, t);
t += Time.deltaTime / timeToReachValues;
timePassed += Time.deltaTime;
if (t >= 1) {
transform.localScale = targetScale;
transform.position = originalSpawnPos;
}
yield return new WaitForEndOfFrame ();
}
OnReturnToSpawnPointRoutine = null;
}
public void OnDrag ()
{
if (OnDragRoutine == null) {
isBeingDragged = true;
OnDragRoutine = DOOnDragRoutine ();
if (OnReturnToSpawnPointRoutine != null) {
StopCoroutine (OnReturnToSpawnPointRoutine);
}
StartCoroutine (OnDragRoutine);
}
}
public void StopDrag ()
{
if (OnDragRoutine != null) {
isBeingDragged = false;
StopCoroutine (OnDragRoutine);
OnDragRoutine = null;
}
}
public IEnumerator OnDragRoutine;
public IEnumerator DOOnDragRoutine ()
{
float timeToReachValues = 0.1f;
float t = 0;
float timePassed = 0;
Vector3 startPos = transform.position;
Vector3 startScale = transform.localScale;
while (t <= 1 && isBeingDragged) {
transform.localScale = Vector3.Lerp (startScale, originalScale, t);
transform.position = Vector3.Lerp (startPos, GetFollowMousePos (), t);
t += Time.deltaTime / timeToReachValues;
timePassed += Time.deltaTime;
if (t >= 1) {
transform.localScale = originalScale;
}
yield return new WaitForEndOfFrame ();
}
while (isBeingDragged) {
transform.position = GetFollowMousePos ();
yield return new WaitForEndOfFrame ();
}
}
public Vector3 GetFollowMousePos ()
{
float distanceBetweenCenterAndTetrimoMinPoint = Mathf.Abs (_centroid.y - _minAndMaxPoints [0].y);
Vector3 worldMousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
worldMousePos.z = transform.position.z;
worldMousePos.y += distanceBetweenCenterAndTetrimoMinPoint + 1.15f;
return worldMousePos;
}
public void OnDisable ()
{
Vector3 targetScale = originalScale * TetrimoSpawner.instance.scaleFactorOnSpawnPoint;
transform.position = originalSpawnPos;
transform.localScale = targetScale;
}
and here is the code that is attached to every square pieces that makes up the prefab:
public BoxCollider2D coll;
public GridPiece lastNearestGridPiece;
private SpriteRenderer _spriteRenderer;
public int SortingOrder {
get {
return spriteRenderer.sortingOrder;
}
set {
spriteRenderer.sortingOrder = value;
}
}
public SpriteRenderer spriteRenderer {
get {
if (_spriteRenderer == null) {
_spriteRenderer = GetComponentInChildren<SpriteRenderer> ();
}
return _spriteRenderer;
}
}
void Awake ()
{
coll = GetComponentInChildren<BoxCollider2D> ();
}
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
public Vector2 GetColliderSize ()
{
return coll.bounds.size;
}
public void SetNearestGridPiece ()
{
GridPiece[] gridPieces = Grid.instance.gridPieces.ToArray ();
GridPiece lastNearestGridPieceFound = gridPieces[0];
float lastNearestDistanceFound = Vector3.Distance (gridPieces [0].transform.position, transform.position);
foreach (GridPiece piece in gridPieces) {
float distanceBetweenGridPieceAndThis = Vector3.Distance(piece.transform.position, transform.position);
if (distanceBetweenGridPieceAndThis < lastNearestDistanceFound)
{
lastNearestGridPieceFound = piece;
lastNearestDistanceFound = distanceBetweenGridPieceAndThis;
}
}
lastNearestGridPiece = lastNearestGridPieceFound;
}
public void SetColor (Color color)
{
spriteRenderer.color = color;
}
here is the code for generating grid:
public static Grid instance;
public int rowsCount;
public int columnsCount;
public GridPiecesSet[] rows;
public GridPiecesSet[] columns;
public List<GridPiece> gridPieces;
public float distanceBetweenGroundPieces;
public GridPiece gridPiece;
GridPiecesContainer gridPiecesContainer;
void Awake ()
{
instance = this;
gridPiecesContainer = GetComponentInChildren<GridPiecesContainer> ();
GenerateGrid ();
}
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
//This generates the grid
public void GenerateGrid ()
{
rows = Enumerable.Range (0, columnsCount).Select (i => new GridPiecesSet (columnsCount, GridPiecesSet.Type.row)).ToArray ();
columns = Enumerable.Range (0, rowsCount).Select (i => new GridPiecesSet (rowsCount, GridPiecesSet.Type.column)).ToArray ();
gridPieces = new List<GridPiece> ();
for (int rowsIndex = 0; rowsIndex < rowsCount; rowsIndex++) {
GenerateRow (rowsIndex);
}
gridPiecesContainer.MoveToCenter ();
}
void GenerateRow (int rowsIndex)
{
GridPiece lastSpawnedRowPiece = null;
for (int columnsIndex = 0; columnsIndex < columnsCount; columnsIndex++) {
if (rowsIndex == 0 && columnsIndex == 4 || columnsIndex == 5)
{
GridPiece newGridPiece = Instantiate(gridPiece.gameObject).GetComponent<GridPiece>();
newGridPiece.transform.SetParent(gridPiecesContainer.transform);
Vector3 newPos = newGridPiece.transform.position;
// GENERATING FROM TOP LEFT
newPos.x = (newGridPiece.GetWidth() / 2 + distanceBetweenGroundPieces) * columnsIndex;
newPos.y = (newGridPiece.GetHeight() / 2 + distanceBetweenGroundPieces) * (-rowsIndex);
newGridPiece.transform.position = newPos;
newGridPiece.name = " piece_row_" + rowsIndex + " piece_col_" + columnsIndex;
rows[rowsIndex].gridPieces[columnsIndex] = newGridPiece;
columns[columnsIndex].gridPieces[rowsIndex] = newGridPiece;
gridPieces.Add(newGridPiece);
lastSpawnedRowPiece = newGridPiece.GetComponent<GridPiece>();
}
else if ((columnsIndex >= 3 && columnsIndex <= 6) && rowsIndex == 1)
{
GridPiece newGridPiece = Instantiate(gridPiece.gameObject).GetComponent<GridPiece>();
newGridPiece.transform.SetParent(gridPiecesContainer.transform);
Vector3 newPos = newGridPiece.transform.position;
// GENERATING FROM TOP LEFT
newPos.x = (newGridPiece.GetWidth() / 2 + distanceBetweenGroundPieces) * columnsIndex;
newPos.y = (newGridPiece.GetHeight() / 2 + distanceBetweenGroundPieces) * (-rowsIndex);
newGridPiece.transform.position = newPos;
newGridPiece.name = " piece_row_" + rowsIndex + " piece_col_" + columnsIndex;
rows[rowsIndex].gridPieces[columnsIndex] = newGridPiece;
columns[columnsIndex].gridPieces[rowsIndex] = newGridPiece;
gridPieces.Add(newGridPiece);
lastSpawnedRowPiece = newGridPiece.GetComponent<GridPiece>();
}
else if ((columnsIndex >= 2 && columnsIndex <= 7) && rowsIndex == 2)
{
GridPiece newGridPiece = Instantiate(gridPiece.gameObject).GetComponent<GridPiece>();
newGridPiece.transform.SetParent(gridPiecesContainer.transform);
Vector3 newPos = newGridPiece.transform.position;
// GENERATING FROM TOP LEFT
newPos.x = (newGridPiece.GetWidth() / 2 + distanceBetweenGroundPieces) * columnsIndex;
newPos.y = (newGridPiece.GetHeight() / 2 + distanceBetweenGroundPieces) * (-rowsIndex);
newGridPiece.transform.position = newPos;
newGridPiece.name = " piece_row_" + rowsIndex + " piece_col_" + columnsIndex;
rows[rowsIndex].gridPieces[columnsIndex] = newGridPiece;
columns[columnsIndex].gridPieces[rowsIndex] = newGridPiece;
gridPieces.Add(newGridPiece);
lastSpawnedRowPiece = newGridPiece.GetComponent<GridPiece>();
}
else if ((columnsIndex >= 1 && columnsIndex <= 8) && rowsIndex == 3)
{
GridPiece newGridPiece = Instantiate(gridPiece.gameObject).GetComponent<GridPiece>();
newGridPiece.transform.SetParent(gridPiecesContainer.transform);
Vector3 newPos = newGridPiece.transform.position;
// GENERATING FROM TOP LEFT
newPos.x = (newGridPiece.GetWidth() / 2 + distanceBetweenGroundPieces) * columnsIndex;
newPos.y = (newGridPiece.GetHeight() / 2 + distanceBetweenGroundPieces) * (-rowsIndex);
newGridPiece.transform.position = newPos;
newGridPiece.name = " piece_row_" + rowsIndex + " piece_col_" + columnsIndex;
rows[rowsIndex].gridPieces[columnsIndex] = newGridPiece;
columns[columnsIndex].gridPieces[rowsIndex] = newGridPiece;
gridPieces.Add(newGridPiece);
lastSpawnedRowPiece = newGridPiece.GetComponent<GridPiece>();
}
else if (rowsIndex == 4)
{
GridPiece newGridPiece = Instantiate(gridPiece.gameObject).GetComponent<GridPiece>();
newGridPiece.transform.SetParent(gridPiecesContainer.transform);
Vector3 newPos = newGridPiece.transform.position;
// GENERATING FROM TOP LEFT
newPos.x = (newGridPiece.GetWidth() / 2 + distanceBetweenGroundPieces) * columnsIndex;
newPos.y = (newGridPiece.GetHeight() / 2 + distanceBetweenGroundPieces) * (-rowsIndex);
newGridPiece.transform.position = newPos;
newGridPiece.name = " piece_row_" + rowsIndex + " piece_col_" + columnsIndex;
rows[rowsIndex].gridPieces[columnsIndex] = newGridPiece;
columns[columnsIndex].gridPieces[rowsIndex] = newGridPiece;
gridPieces.Add(newGridPiece);
lastSpawnedRowPiece = newGridPiece.GetComponent<GridPiece>();
}
else if (rowsIndex == 5)
{
GridPiece newGridPiece = Instantiate(gridPiece.gameObject).GetComponent<GridPiece>();
newGridPiece.transform.SetParent(gridPiecesContainer.transform);
Vector3 newPos = newGridPiece.transform.position;
// GENERATING FROM TOP LEFT
newPos.x = (newGridPiece.GetWidth() / 2 + distanceBetweenGroundPieces) * columnsIndex;
newPos.y = (newGridPiece.GetHeight() / 2 + distanceBetweenGroundPieces) * (-rowsIndex);
newGridPiece.transform.position = newPos;
newGridPiece.name = " piece_row_" + rowsIndex + " piece_col_" + columnsIndex;
rows[rowsIndex].gridPieces[columnsIndex] = newGridPiece;
columns[columnsIndex].gridPieces[rowsIndex] = newGridPiece;
gridPieces.Add(newGridPiece);
lastSpawnedRowPiece = newGridPiece.GetComponent<GridPiece>();
}
else if ((columnsIndex >= 1 && columnsIndex <= 8) && rowsIndex == 6)
{
GridPiece newGridPiece = Instantiate(gridPiece.gameObject).GetComponent<GridPiece>();
newGridPiece.transform.SetParent(gridPiecesContainer.transform);
Vector3 newPos = newGridPiece.transform.position;
// GENERATING FROM TOP LEFT
newPos.x = (newGridPiece.GetWidth() / 2 + distanceBetweenGroundPieces) * columnsIndex;
newPos.y = (newGridPiece.GetHeight() / 2 + distanceBetweenGroundPieces) * (-rowsIndex);
newGridPiece.transform.position = newPos;
newGridPiece.name = " piece_row_" + rowsIndex + " piece_col_" + columnsIndex;
rows[rowsIndex].gridPieces[columnsIndex] = newGridPiece;
columns[columnsIndex].gridPieces[rowsIndex] = newGridPiece;
gridPieces.Add(newGridPiece);
lastSpawnedRowPiece = newGridPiece.GetComponent<GridPiece>();
}
else if ((columnsIndex >= 2 && columnsIndex <= 7) && rowsIndex == 7)
{
GridPiece newGridPiece = Instantiate(gridPiece.gameObject).GetComponent<GridPiece>();
newGridPiece.transform.SetParent(gridPiecesContainer.transform);
Vector3 newPos = newGridPiece.transform.position;
// GENERATING FROM TOP LEFT
newPos.x = (newGridPiece.GetWidth() / 2 + distanceBetweenGroundPieces) * columnsIndex;
newPos.y = (newGridPiece.GetHeight() / 2 + distanceBetweenGroundPieces) * (-rowsIndex);
newGridPiece.transform.position = newPos;
newGridPiece.name = " piece_row_" + rowsIndex + " piece_col_" + columnsIndex;
rows[rowsIndex].gridPieces[columnsIndex] = newGridPiece;
columns[columnsIndex].gridPieces[rowsIndex] = newGridPiece;
gridPieces.Add(newGridPiece);
lastSpawnedRowPiece = newGridPiece.GetComponent<GridPiece>();
}
else if ((columnsIndex >= 3 && columnsIndex <= 6) && rowsIndex == 8)
{
GridPiece newGridPiece = Instantiate(gridPiece.gameObject).GetComponent<GridPiece>();
newGridPiece.transform.SetParent(gridPiecesContainer.transform);
Vector3 newPos = newGridPiece.transform.position;
// GENERATING FROM TOP LEFT
newPos.x = (newGridPiece.GetWidth() / 2 + distanceBetweenGroundPieces) * columnsIndex;
newPos.y = (newGridPiece.GetHeight() / 2 + distanceBetweenGroundPieces) * (-rowsIndex);
newGridPiece.transform.position = newPos;
newGridPiece.name = " piece_row_" + rowsIndex + " piece_col_" + columnsIndex;
rows[rowsIndex].gridPieces[columnsIndex] = newGridPiece;
columns[columnsIndex].gridPieces[rowsIndex] = newGridPiece;
gridPieces.Add(newGridPiece);
lastSpawnedRowPiece = newGridPiece.GetComponent<GridPiece>();
}
else if ((columnsIndex >= 4 && columnsIndex <= 5) && rowsIndex == 9)
{
GridPiece newGridPiece = Instantiate(gridPiece.gameObject).GetComponent<GridPiece>();
newGridPiece.transform.SetParent(gridPiecesContainer.transform);
Vector3 newPos = newGridPiece.transform.position;
// GENERATING FROM TOP LEFT
newPos.x = (newGridPiece.GetWidth() / 2 + distanceBetweenGroundPieces) * columnsIndex;
newPos.y = (newGridPiece.GetHeight() / 2 + distanceBetweenGroundPieces) * (-rowsIndex);
newGridPiece.transform.position = newPos;
newGridPiece.name = " piece_row_" + rowsIndex + " piece_col_" + columnsIndex;
rows[rowsIndex].gridPieces[columnsIndex] = newGridPiece;
columns[columnsIndex].gridPieces[rowsIndex] = newGridPiece;
gridPieces.Add(newGridPiece);
lastSpawnedRowPiece = newGridPiece.GetComponent<GridPiece>();
}
}
}
public bool IsGameOver ()
{
bool gameOver = true;
foreach (Tetrimo tetrimo in TetrimoSpawner.instance.spawnedTetrimos) {
if (tetrimo != null) {
if (tetrimo.CanFitInGrid ()) {
gameOver = false;
break;
}
}
}
return gameOver;
}
public void CleanCompletedRowsAndColumns ()
{
List<GridPiecesSet> rowsAndColumnsToClean = new List<GridPiecesSet> ();
foreach (GridPiecesSet row in rows) {
if (row.AllPiecesFilled () && row.colorMatch()) {
rowsAndColumnsToClean.Add (row);
}
}
foreach (GridPiecesSet column in columns) {
if (column.AllPiecesFilled () && column.colorMatch()) {
rowsAndColumnsToClean.Add (column);
}
}
if (rowsAndColumnsToClean.Count > 0) {
ClearAllCompletedRowsAndColumns (rowsAndColumnsToClean);
}
}
public void ClearAllCompletedRowsAndColumns (List<GridPiecesSet> rowsAndColumnsToClean)
{
SoundsManager.instance.PlayLineCompleted ();
foreach (GridPiecesSet pieceSet in rowsAndColumnsToClean) {
pieceSet.Clean ();
StartCoroutine (DOCleanAnimation (pieceSet));
}
}
public void ClearGrid ()
{
foreach (GridPiece gridPiece in gridPieces) {
gridPiece.SetFilled (false);
}
}
public GridPieceConfiguration[] GetCurrentGridConfiguration ()
{
GridPieceConfiguration[] gridConfig = new GridPieceConfiguration[gridPieces.Count ()];
int count = 0;
foreach (GridPiece gridPiece in gridPieces) {
gridConfig [count] = new GridPieceConfiguration ();
gridConfig [count].ActivationState = gridPiece.isFilled;
gridConfig [count].TetrimoThatFillsName = gridPiece.tetrimoPieceThatFillsMeName;
count++;
}
return gridConfig;
}
public void TurnOffAllTutorialFillablePieces ()
{
foreach (GridPiece piece in gridPieces) {
piece.SetIlluminated (false);
piece.SetTutorialFillable (false);
}
}
public void SetGridByConfiguration (GridPieceConfiguration[] configs)
{
int count = 0;
foreach (GridPieceConfiguration config in configs) {
GridPiece iteratedPiece = gridPieces [count];
if (config.ActivationState == true) {
iteratedPiece.SetFilled (true);
Tetrimo tetrimoThatFillsGridPiece = Resources.Load<Tetrimo> ("Tetrimos/" + config.TetrimoThatFillsName);
if (tetrimoThatFillsGridPiece == null) {
throw new UnassignedReferenceException ();
}
iteratedPiece.SetTetrimoThatFillsMe (tetrimoThatFillsGridPiece);
} else {
iteratedPiece.SetFilled (false);
}
iteratedPiece.SetIlluminated (false);
iteratedPiece.SetTutorialFillable (true);
count++;
}
}
public IEnumerator DOCleanAnimation (GridPiecesSet piecesSet)
{
List<GridPiece> gridPiecesToAnimate = new List<GridPiece> ();
foreach (GridPiece piece in piecesSet.gridPieces) {
if (piece != null)
{
GridPiece clonePiece = GameObject.Instantiate(piece.gameObject).GetComponent<GridPiece>();
clonePiece.transform.position = piece.transform.position;
clonePiece.graphicWhenFilled.sortingOrder += 10;
clonePiece.SetFilled(true);
gridPiecesToAnimate.Add(clonePiece);
}
}
foreach (GridPiece piece in gridPiecesToAnimate) {
if (piece != null)
{
StartCoroutine(DisappearAnim(piece, piecesSet));
yield return new WaitForSeconds(0.07f);
}
}
yield return new WaitForEndOfFrame ();
}
IEnumerator DisappearAnim (GridPiece piece, GridPiecesSet piecesSet)
{
float t = 0;
float animTime = 0.15f;
Vector3 startScale = piece.transform.localScale;
Vector3 targetScale = Vector3.zero;
while (t <= 1) {
piece.transform.localScale = Vector3.Lerp (startScale, targetScale, t);
t += Time.deltaTime / animTime;
yield return new WaitForEndOfFrame ();
if (t >= 1) {
piece.transform.localScale = targetScale;
}
}
piece.DestroySelf ();
}
and finally the inputhandler that handles input from mouse or touch
bool isDragging = false;
Tetrimo tetrimoToMove = null;
// Use this for initialization
void Start ()
{
}
void Update ()
{
if (Input.GetMouseButtonDown (0)) {
OnMouseButtonDown ();
}
if (Input.GetMouseButtonUp (0)) {
OnMouseButtonUp ();
}
if (isDragging) {
OnDrag ();
}
}
public void OnDrag ()
{
tetrimoToMove.OnDrag ();
}
public void OnMouseButtonUp ()
{
if (isDragging) {
if (tetrimoToMove.CanBeReleasedOverGrid ()) {
Debug.Log("Mouse Up");
if (TutorialManager.instance.isShowingTutorial) {
StartCoroutine (TutorialManager.instance.OnTetrimoReleasedOverGrid ());
}
SoundsManager.instance.PlayTetrimoPlacement ();
tetrimoToMove.PlaceOverGrid ();
Grid.instance.CleanCompletedRowsAndColumns ();
if (Grid.instance.IsGameOver () && !TetrimoSpawner.instance.HasToSpawnNewTetrimos () && !TutorialManager.instance.isShowingTutorial) {
StartCoroutine(ObliusGameManager.instance.GameOver ());
Debug.Log ("GAME OVER");
} else {
Debug.Log ("GAME CAN CONTINUE");
}
if (!TutorialManager.instance.isShowingTutorial) {
GameStateSerializer.SaveCurrentState (Grid.instance, TetrimoSpawner.instance, ScoreHandler.instance);
}
if (!TutorialManager.instance.isShowingTutorial && TetrimoSpawner.instance.HasToSpawnNewTetrimos()) {
StartCoroutine (TetrimoSpawner.instance.TetrimoSpawnRoutine (true));
}
} else {
tetrimoToMove.StopDrag ();
tetrimoToMove.ReturnToSpawnPoint (0.1f);
}
}
isDragging = false;
}
public void OnMouseButtonDown ()
{
if (!isDragging && ObliusGameManager.instance.gameState != ObliusGameManager.GameState.gameover) {
tetrimoToMove = GetClickedTetrimo ();
if (tetrimoToMove != null) {
if (TutorialManager.instance.isShowingTutorial) {
if (tetrimoToMove.assignedSpawnPoint != TutorialManager.instance.currentShownTutorialStep.clickableSpawnPoint) {
isDragging = false;
return;
}
TutorialManager.instance.tutorialhand.StopMoveAndHide ();
}
isDragging = true;
} else {
isDragging = false;
}
}
}
public Tetrimo GetClickedTetrimo ()
{
Tetrimo clickedTetrimo = null;
Vector3 mousePos = Input.mousePosition;
mousePos.z = 10;
Vector3 screenPos = Camera.main.ScreenToWorldPoint (mousePos);
RaycastHit2D hit = Physics2D.Raycast (screenPos, Vector2.zero);
if (hit) {
Tetrimo hitTetrimo = hit.transform.GetComponentInParent<Tetrimo> ();
TetrimoSpawnPoint hitSpawnPoint = hit.transform.GetComponent<TetrimoSpawnPoint> ();
if (hitTetrimo != null) {
clickedTetrimo = hitTetrimo;
} else if (hitSpawnPoint != null) {
clickedTetrimo = hitSpawnPoint.assignedTetrimo;
Debug.Log ("Spawn point hit");
}
}
return clickedTetrimo;
}

How to control the jump of my RigidbodyFPSController?

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.

Drag an object in User Defined Target of vuforia Unity3d

I am working on User Defined Target package of vuforia. Package is working gud but i have problem when i try to drag my 3d model.
That code is working without UserDefinedTarget.
Code is here :
GameObject target = GameObject.FindGameObjectWithTag("Target");
if(Input.touchCount == 1)
{
if (theTouch.phase == TouchPhase.Began)
{
Debug.Log("Touch phase began at: " + theTouch.position);
RaycastHit hit = new RaycastHit();
if (Physics.Raycast(ray, out hit, maxPickingDistance))
{
pickedObject = target.transform;
}
else
{
pickedObject = null;
}
}
else if (theTouch.phase == TouchPhase.Moved)
{
Debug.Log("Touch phase Moved");
if (pickedObject != null)
{
Vector3 translationInCameraRef;
Vector2 screenDelta = theTouch.deltaPosition;
float halfScreenWidth = 0.5f * Screen.width;
float halfScreenHeight = 0.5f * Screen.height;
float dx = screenDelta.x / halfScreenWidth;
float dy = screenDelta.y / halfScreenHeight;
Vector3 objectToCamera =
pickedObject.transform.position - Camera.main.transform.position;
float distance = objectToCamera.magnitude;
float fovRad = Camera.main.fieldOfView * Mathf.Deg2Rad;
float motionScale = distance * Mathf.Tan(fovRad/2);
if(Application.loadedLevelName == "LoadModel")
{
translationInCameraRef =
new Vector3(motionScale * dx, motionScale * dy, 0);
}
else{
translationInCameraRef =
new Vector3(motionScale * dx , motionScale * dy , motionScale * dy);
}
Vector3 translationInWorldRef =
Camera.main.transform.TransformDirection(translationInCameraRef);
pickedObject.position += translationInWorldRef * 5.0f;
}
}
else if (theTouch.phase == TouchPhase.Ended)
{
Debug.Log("Touch phase Ended");
pickedObject = null;
}
}
CAn anyone is having any idea regarding this ? Please help me to solve out this.
Thanks.