- Home /
Question by
Galiza · Jul 17, 2015 at 04:00 AM ·
programmingswipe
Having problems with my swipe
Hi, I'm currently making a game with swipe, though sometimes the swipe doesn't work, I'll leave the code here, so please, someone, help me out.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class Snake : MonoBehaviour
{
//SWIPE
private Vector3 fp; //primeira posiçao de toque
private Vector3 lp; //ultima posiçao de toque
private float dragDistance; //distancia minima pro swipe ser marcado
private List<Vector3> touchPositions = new List<Vector3>(); //armazena todos os toques
public Sprite sprite1;
public Sprite sprite2;
public Sprite sprite3;
public Sprite sprite4;
private SpriteRenderer spriteRenderer;
// Main script for all the snake logic
// Mobile controls
//#if UNITY_IPHONE || UNITY_ANDROID || UNITY_WP8
// Left button game object
//GameObject leftButton;
// Right button game object
//GameObject rightButton;
// Rotate button game object
//GameObject upButton;
// Down button game object
//GameObject downButton;
//#endif
public GameObject spritehead;
// Current Movement Direction
// (by default it moves to the right)
Vector2 dir = Vector2.right;
// Keep Track of Tail
List<Transform> body = new List<Transform>();
// Body Prefab
public GameObject bodyPrefab;
//Tail Prefab
public GameObject tailPrefab; //Yuri: adicionei
// Bool used to store if snake has ate something
bool ate = false;
// Spawner GameObject
GameObject spawner;
// Reference to the spawneScript
Spawner spawnerScript;
// Used for player's score
public static int score = 0;
public int foodScore = 10;
public int bonusScore = 50;
// Use for the controls
bool facingLeftOrRight = false;
bool facingUpOrDown = false;
bool left = false;//venyton: adicionei
//COMO INICIALMENTE A SNAKE SE MOVE PRA DIREITA, right DEVE SEMPRE COMEÇAR COMO true
bool right = true;//venyton: adicionei
bool up = false;//venyton: adicionei
bool down = false;//venyton: adicionei
// Sounds
public AudioClip eatSound;
public AudioClip bonusSound;
public AudioClip gameOverSound;
public AudioClip trilhaSonora;
//T <- TAILPREFAB
private GameObject t;
// Bool to say if the game is over
public static bool gameOver = false;
//Vector3 _origPos;
// Use this for initialization
void Start()
{
dragDistance = Screen.height * 10 / 100; //dragDistance e 10% da altura da tela
spriteRenderer = GetComponent<SpriteRenderer> ();
//INSTANCIA TAIL NA POSICAO DA CABEÇA
Vector2 posTail = transform.position;
t = (GameObject)Instantiate (tailPrefab, posTail, Quaternion.identity);
// Assign the mobile controls
//#if UNITY_IPHONE || UNITY_ANDROID || UNITY_WP8
//leftButton = GameObject.Find ("arrow_left_button");
//rightButton = GameObject.Find ("arrow_right_button");
//downButton = GameObject.Find ("arrow_down_button");
//upButton = GameObject.Find ("arrow_up_button");
// #endif
// Moves the Snake every 200ms
InvokeRepeating("Move", 0.2f, 0.2f);
// Match up the spawner GameObject and
// assign the script component
spawner = GameObject.Find("Spawner");
spawnerScript = spawner.GetComponent<Spawner>();
}
//define a direçao em que o dragao esta indo
void SetDirection(string direction){//venyton: adicionei
switch(direction){
case "up":
left = false;
right = false;
up = true;
down = false;
break;
case "down":
left = false;
right = false;
up = false;
down = true;
break;
case "left":
left = true;
right = false;
up = false;
down = false;
break;
case "right":
left = false;
right = true;
up = false;
down = false;
break;
default:
left = false;
right = true;
up = false;
down = false;
break;
}
if(up){
spritehead.transform.eulerAngles = new Vector2(0, 90);
Debug.Log("up");
} else if(down){
spritehead.transform.eulerAngles = new Vector2(0, -90);
Debug.Log("down");
} else if(left){
spritehead.transform.eulerAngles = new Vector2(180, 0);
Debug.Log("left");
} else if(right){
spritehead.transform.eulerAngles = new Vector2(0, 0);
Debug.Log("right");
}
}
void Update()
{
//SWIPE
foreach (Touch touch in Input.touches) //use loop to detect more than one swipe
{ //can be ommitted if you are using lists
if (touch.phase == TouchPhase.Began) //check for the first touch
{
fp = touch.position;
lp = touch.position;
}
if (touch.phase == TouchPhase.Moved) //add the touches to list as the swipe is being made
{
touchPositions.Add(touch.position);
}
if (touch.phase == TouchPhase.Ended) //check if the finger is removed from the screen
{
//lp = touch.position; //last touch position. Ommitted if you use list
fp = touchPositions[0]; //get first touch position from the list of touches
lp = touchPositions[touchPositions.Count - 1]; //last touch position
//Check if drag distance is greater than 20% of the screen height
if (Mathf.Abs(lp.x - fp.x) > dragDistance || Mathf.Abs(lp.y - fp.y) > dragDistance)
{//It's a drag
//check if the drag is vertical or horizontal
if (Mathf.Abs(lp.x - fp.x) > Mathf.Abs(lp.y - fp.y))
{ //If the horizontal movement is greater than the vertical movement...
//CHECA A DIREÇÃO DO SWIPE E GARANTE QUE ENQUANTO ELA SE MOVE PRA DIREITA, NÃO PODE SE MOVER PRA ESQUERDA
if ((lp.x > fp.x) && !left) //If the movement was to the right)
{ //Right swipe
// Debug.Log("Right Swipe");
spriteRenderer.sprite = sprite3;
dir = Vector2.right;
left = false;
right = true;
up = false;
down = false;
}
//MESMA COISA, ENQUANTO ELA SE MOVE PRA ESQUERDA, NÃO PODE SE MOVER PRA DIREITA
else if ((lp.x < fp.x) && !right)
{ //Left swipe
//Debug.Log("Left Swipe");
spriteRenderer.sprite = sprite4;
dir = -Vector2.right;
left = true;
right = false;
up = false;
down = false;
}
}
else
{ //the vertical movement is greater than the horizontal movement
//MESMA COISA, ENQUANTO ELA SE MOVE PRA CIMA, NÃO PODE SE MOVER PRA BAIXO
if ((lp.y > fp.y) && !down) //If the movement was up
{ //Up swipe
spriteRenderer.sprite = sprite1;
dir = Vector2.up;
left = false;
right = false;
up = true;
down = false;
//Debug.Log("Up Swipe");
}
//MESMA COISA, ENQUANTO ELA SE MOVE PRA BAIXO, NÃO PODE SE MOVER PRA CIMA
else if((lp.y < fp.y) && !up)
{ //Down swipe
//Debug.Log("Down Swipe");
spriteRenderer.sprite = sprite2;
dir = -Vector2.up;
left = false;
right = false;
up = false;
down = true;
}
}
}
}
#region MyRegion
// Mobile control logic
// Note the two bools (facingLeftOrRight and facingUpOrDown)
// prevents the snake from colliding with itself in an unwanted manner
//#if UNITY_IPHONE || UNITY_ANDROID || UNITY_WP8
// if click or tap happens
// if (Input.GetMouseButtonDown(0))
// {
// Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
// // checks if an object has been selected
// Collider2D hitCollider = Physics2D.OverlapPoint(mousePosition);
// // button logic
// if (hitCollider)
// {
// if (hitCollider.transform == rightButton.transform)
// {
// if (!facingLeftOrRight)
// {
// spriteRenderer.sprite = sprite3;
// dir = Vector2.right;
// left = false;
// right = true;
// up = false;
// down = false;
// }
// } else if (hitCollider.transform == downButton.transform)
// {
// if (!facingUpOrDown)
// {
// spriteRenderer.sprite = sprite2;
// dir = -Vector2.up;
// left = false;
// right = false;
// up = false;
// down = true;
// }
// } else if (hitCollider.transform == leftButton.transform)
// {
// if (!facingLeftOrRight)
// {
// spriteRenderer.sprite = sprite4;
// dir = -Vector2.right;
// left = true;
// right = false;
// up = false;
// down = false;
// }
// } else if (hitCollider.transform == upButton.transform)
// {
// if (!facingUpOrDown)
// {
// spriteRenderer.sprite = sprite1;
// dir = Vector2.up;
// left = false;
// right = false;
// up = true;
// down = false;
// }
// }
//
// }
// }
//
//#else
#endregion
#if UNITY_PC
Desktop controls
if (Input.GetKey(KeyCode.RightArrow))
{
if (!facingLeftOrRight)
{
spriteRenderer.sprite = sprite3;
dir = Vector2.right;
left = false;
right = true;
up = false;
down = false;
}
}
else if (Input.GetKey(KeyCode.DownArrow))
{
if (!facingUpOrDown)
{
spriteRenderer.sprite = sprite2;
dir = -Vector2.up;
left = false;
right = false;
up = false;
down = true;
}
}
else if (Input.GetKey(KeyCode.LeftArrow))
{
if (!facingLeftOrRight)
{
spriteRenderer.sprite = sprite4;
dir = -Vector2.right;
left = true;
right = false;
up = false;
down = false;
}
}
else if (Input.GetKey(KeyCode.UpArrow))
{
if (!facingUpOrDown)
{
spriteRenderer.sprite = sprite1;
dir = Vector2.up;
left = false;
right = false;
up = true;
down = false;
}
}
#endif
}
if (body.Count == 0)
{
t.transform.eulerAngles = new Vector3(0, 0, Mathf.Atan2((transform.position.y - t.transform.position.y), (transform.position.x - t.transform.position.x)) * Mathf.Rad2Deg);
}
else
{
t.transform.eulerAngles = new Vector3(0, 0, Mathf.Atan2((body.Last().position.y - t.transform.position.y), (body.Last().position.x - t.transform.position.x)) * Mathf.Rad2Deg);
}
}
void Move()
{
// Save current position
Vector2 v = transform.position;
//ENQUANTO SNAKE NAO COMER NENHUMA FOOD, A POSICAO DO RABO CONTINUA A MESMA
if(body.Count == 0)
{
t.transform.position = v;
}
// Move head into new direction
transform.Translate (dir);
// Insert new element if the snake has eaten
if (ate) {
// Load Prefab
GameObject g = (GameObject)Instantiate (bodyPrefab, v, Quaternion.identity);
// Keep track of it the tail list
body.Insert (0, g.transform);
// Reset the ate bool
ate = false;
}
// Is there a tail
else if (body.Count > 0) {
// Move last Tail to where the Head was
//ATUALIAZA A POSICAO DO RABO PARA A POSICAO DO ULTIMO "CORPO"
t.transform.position = body.Last().position;
body.Last ().position = v;
// Add to front of list and remove from the back
body.Insert (0, body.Last ());
body.RemoveAt (body.Count - 1);
}
}
// public void Rotate()
// {
// Quaternion r = Quaternion.LookRotation (Vector3.forward, SetDirection);
//
// }
//
void OnTriggerEnter2D(Collider2D coll)
{
// If the snake eats food
if (coll.name.StartsWith("Food"))
{
// Make the snake longer
ate = true;
// Destroy food
Destroy(coll.gameObject);
// Add to score
score += foodScore;
// Spawn more food
spawnerScript.SpawnFood();
// Play eat sound
GetComponent<AudioSource>().PlayOneShot(eatSound);
// If the snake eats a bonus
} else if (coll.name.StartsWith("Bonus"))
{
// Make the snake longer
ate = true;
// Destroy bonus
Destroy(coll.gameObject);
// Add to score
score += bonusScore;
// Play bonus sound
GetComponent<AudioSource>().PlayOneShot(bonusSound);
}
// Collided with Tail or a Border
else
{
// Set gameOver to true
gameOver = true;
// Stop the snake from moving
CancelInvoke();
// Play gameOverSound
GetComponent<AudioSource>().PlayOneShot(gameOverSound);
}
}
}
Comment
A lot of code and a very small amount to go on.
Any errors in the log? Have you used Debug.Log() to see whats going on?
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Android wear swipe to dismiss 0 Answers
I made a better shader how do i fix[add _Shadow Strength]help???>Sorry that im asking for to much 1 Answer
Unity swipe controlls mobile 0 Answers
Bool is not turning false 1 Answer