GetPixel makes the game slow - unity3d

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

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

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

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

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.

No Script Errors - Character doesnt jump - Unity 3d

Currently building a 2D game, and have created a javascript code for the jump for my character 'Ezio' but it does not do anything when i press 'space' for it to jump. There are no errors with the code either.
#pragma strict
var jump :float = 0;
var jumpspeed : float = 15;
var jumptimer :float = 0;
function Start () {
}
function Update () {
if (jump == 1) {
jumptimer = jumptimer +1;
if (jumptimer >= 50) {
jumptimer = 0;
jump = 0;
}
}
}
if (Input.GetKeyDown ("space"))
{
if (jump == 0) {
rigidbody2D.velocity.y = jumpspeed;
jump = 1;
}
}
Any suggestions on what could be the issue?
Try this:
#pragma strict
var jump :float = 0;
var jumpspeed : float = 15;
var jumptimer :float = 0;
function Start () {
}
function Update() {
if (Input.GetKeyDown("space")) {
if (jump == 1) {
jumptimer = jumptimer + 1;
if (jumptimer >= 50) {
jumptimer = 0;
jump = 0;
}
} else {
rigidbody2D.velocity.y = jumpspeed;
jump = 1;
}
}
}