Controlling swipe inputs in unity - c#

I am practicing in Unity; I want to move an object to the right and left according to how I swipe. I have gotten the script so far but the problem occurs when I am playing it. It is setting the objects location to the center; swipe actions are working just fine. However, I don't want it to set the object to the center.
Script:
public class swipeTest : MonoBehaviour {
public SwipeManager swipeControls;
public Transform Player;
private Vector3 desiredPosition;
private void Update() {
if (swipeControls.SwipeLeft)
desiredPosition += Vector3.left;
if (swipeControls.SwipeRight)
desiredPosition += Vector3.right;
Player.transform.position = Vector3.MoveTowards
(Player.transform.position, desiredPosition, 0.5f * Time.deltaTime);
}
}
And Another
public class SwipeManager : MonoBehaviour {
private bool tap, swipeLeft, swipeRight, swipeUp, swipeDown;
private bool isDraging = false;
private Vector2 startTouch, swipeDelta;
public Vector2 SwipeDelta { get { return swipeDelta; } }
public bool Tap { get { return tap; } }
public bool SwipeLeft { get { return swipeLeft; } }
public bool SwipeRight { get { return swipeRight; } }
public bool SwipeUp { get { return swipeUp; } }
public bool SwipeDown { get { return swipeDown; } }
private void Update() {
tap = swipeLeft = swipeRight = swipeUp = swipeDown = false;
#region Standalone Inputs
if (Input.GetMouseButtonDown(0)) {
tap = true;
isDraging = true;
startTouch = Input.mousePosition;
}
else if (Input.GetMouseButtonUp(0)) {
isDraging = false;
Reset();
}
#endregion
#region Mobile Input
if (Input.touches.Length > 0) {
if (Input.touches[0].phase == TouchPhase.Began) {
isDraging = true;
tap = true;
startTouch = Input.touches[0].position;
}
else if (Input.touches[0].phase == TouchPhase.Ended || Input.touches[0].phase == TouchPhase.Canceled) {
isDraging = false;
Reset();
}
}
#endregion
// Calculate the distance
swipeDelta = Vector2.zero;
if (isDraging) {
if (Input.touches.Length > 0)
swipeDelta = Input.touches[0].position - startTouch;
else if (Input.GetMouseButton(0))
swipeDelta = (Vector2)Input.mousePosition - startTouch;
}
//Did we cross the distance?
if (swipeDelta.magnitude > 125) {
//Which direction?
float x = swipeDelta.x;
float y = swipeDelta.y;
if (Mathf.Abs(x) > Mathf.Abs(y)) {
//Left or right
if (x < 0)
swipeLeft = true;
else
swipeRight = true;
}
else {
// Up or down
if (y < 0)
swipeDown = true;
else
swipeUp = true;
}
Reset();
}
}
void Reset() {
startTouch = swipeDelta = Vector2.zero;
isDraging = false;
}
}

It seems like you never initialised desiredPosition in your code.
I did not successfully reproduce your issue, but theoretically I believe this should work. Please let us know if it helped.
Assuming no other forces act on the Player tranform (it won't be moved other than by this script):
public class swipeTest : MonoBehaviour {
private void Start() {
desiredPosition = Player.position;
}
}
Or if other forces act on Player you should update it every time:
public class swipeTest : MonoBehaviour {
private void Update() {
desiredPosition = Player.position;
if (swipeControls.SwipeLeft)
desiredPosition += Vector3.left;
if (swipeControls.SwipeRight)
desiredPosition += Vector3.right;
Player.transform.position = Vector3.MoveTowards
(Player.transform.position, desiredPosition, 0.5f * Time.deltaTime);
}
}

Related

I get Unity error "cannot access componet because of accessibility"

Here is my C# code:
using UnityEngine;
using UnityEngine.AI;
public class ShootingAi : MonoBehaviour
{
public NavMeshAgent agent;
public Animator animator;
public CharacterController cc;
public Transform player, wallCheck;
public GameObject gun;
//Movement && Stats
public int health;
public float walkSpeed, runSpeed, gravityMultiplier;
//Check for Ground/Obstacles
public LayerMask whatIsGround, whatIsPlayer,whatIsObject,whatIsAll;
//Patroling
public Vector3 walkPoint;
public Vector2 distanceToWalkPoint;
public bool walkPointSet;
public float walkPointRange;
//Attack Player
public float timeBetweenAttacks;
bool alreadyShot;
//State machine
public bool isPatroling, isChasing, isAttacking, isDead;
public float sightRange, attackRange;
public bool grounded, playerInSightRange, playerInAttackRange, blockingObject;
//Stupid gunAnimFix :D
public GameObject walkPointGraphic;
public GameObject gunRunning, gunWalking, gunShooting;
private void Awake()
{
player = GameObject.Find("PlayerObj").transform;
}
private void Update()
{
StateMachine();
Movement();
AnimationController();
//SetWalkPoint
//if (walkPointGraphic != null)
//walkPointGraphic.transform.position = new Vector3(walkPoint.x, 1.738182f, walkPoint.z);
}
private void AnimationController()
{
if (isPatroling) animator.SetBool("walking", true);
else animator.SetBool("walking", false);
if (isAttacking) animator.SetBool("shooting", true);
else animator.SetBool("shooting", false);
if (isChasing) animator.SetBool("running", true);
else animator.SetBool("running", false);
if (isDead) animator.SetBool("dead", true);
else animator.SetBool("dead", false);
//Don't copy to other projects...
if (isPatroling) gunWalking.SetActive(true);
else gunWalking.SetActive(false);
if (isAttacking) gunShooting.SetActive(true);
else gunWalking.SetActive(false);
if (isChasing) gunRunning.SetActive(true);
else gunRunning.SetActive(false);
}
private void Movement()
{
//extra gravity
cc.Move(-transform.up * Time.deltaTime * gravityMultiplier);
}
private void StateMachine()
{
if (!isDead){
//Check if Player in sightrange
playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);
//Check if Player in attackrange
playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);
if ((!playerInSightRange && !playerInAttackRange)|| blockingObject) Patroling();
if (playerInSightRange && !playerInAttackRange && !blockingObject) ChasePlayer();
if (playerInAttackRange && playerInSightRange && !blockingObject) AttackPlayer();
}
}
private void Patroling()
{
if (isDead) return;
isPatroling = true;
isChasing = false;
isAttacking = false;
//Calculates DistanceToWalkPoint
distanceToWalkPoint = new Vector2(Mathf.Abs(walkPoint.x) - Mathf.Abs(transform.position.x), Mathf.Abs(walkPoint.z) - Mathf.Abs(transform.position.z));
if (!walkPointSet) SearchWalkPoint();
//Calculate direction and walk to Point
if (walkPointSet){
agent.SetDestination(walkPoint);
Vector3 direction = walkPoint - transform.position;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), 0.15f);
}
//Walkpoint reached
if (distanceToWalkPoint.x < 1f && distanceToWalkPoint.y < 1f)
walkPointSet = false;
}
private void SearchWalkPoint()
{
if (isDead) return;
float randomZ = Random.Range(-walkPointRange, walkPointRange);
float randomX = Random.Range(-walkPointRange, walkPointRange);
walkPoint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);
if (Physics.Raycast(walkPoint,-transform.up, 2,whatIsGround))
walkPointSet = true;
}
private void ChasePlayer()
{
if (isDead) return;
isPatroling = false;
isChasing = true;
isAttacking = false;
//Direction Calculate && move
agent.SetDestination(player.position);
Vector3 direction = player.position - transform.position;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), 0.15f);
}
private void AttackPlayer()
{
if (isDead) return;
isPatroling = false;
isChasing = false;
isAttacking = true;
transform.LookAt(new Vector3(player.position.x,player.position.y, player.position.z));
if (!alreadyShot){
gun.GetComponent<Gun>().Shoot();
alreadyShot = true;
Invoke("ResetShot", timeBetweenAttacks);
}
}
private void ResetShot()
{
if (isDead) return;
alreadyShot = false;
}
public void TakeDamage(int damage)
{
health -= damage;
if (health < 0){
isDead = true;
isAttacking = false;
isChasing = false;
isPatroling = false;
Invoke("Destroyy", 2.8f);
}
}
private void Destroyy()
{
Destroy(gameObject);
}
}
And I get this error:
Severity Code Description Project File Line Suppression State
Error CS0122 'Gun.Shoot()' is inaccessible due to its protection level Assembly-CSharp C:\Users\staff\Downloads\EnemyAi (Project file) woLibrary\Assets\Stuff\EnemyChar\ShootingAi.cs 156 Active
I am running on unity version 2020.3.12f1
And my gun.shoot() script is:
public void Shoot()
{
readyToShoot = false;
//RayCast
if (Physics.Raycast(transform.position, enemy.forward, out rayHit, range, whatIsPlayer))
{
if (rayHit.collider.gameObject.GetComponent<playerMovement>())
//rayHit.collider.GetComponent<playerMovement>().TakeDamage(damage);
Debug.Log(rayHit.collider.gameObject.name);
}
bulletsLeft--;
Instantiate(muzzleFlash, attackPos.position, Quaternion.identity);
Invoke("ShotReset", timeBetweenShooting);
}

Unity2D-How to restore hearts after destroying them when Player gets hit

I am using Destroy(Corazones[0].gameObject); to destroy 5 hearts in an array, but I need to restore them when the player gets another heart. I already have the collider that increases lives +1 and it works, but I do not know how to respawn the heart that represents that life.
The hearts get destroyed when the player gets Hit(); but I also need for the hearts to get restored with Vida(); which increases the live +1
Thanks for your help!
This is the way the hearts look
My code uses spanish words.
PD: I know my code is a mess, but works for the other stuff.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityStandardAssets.CrossPlatformInput;
using UnityEngine.UI;
public class DixonMovement : MonoBehaviour
{
public GameObject PildoraPrefab;
public float Speed;
public float JumpForce;
public AudioClip Golpe;
public AudioClip Salto;
public AudioClip Muerte;
public AudioClip Caida;
public GameObject[] Corazones;
private Rigidbody2D Rigidbody2D;
private Animator Animator;
private float Horizontal;
private bool Grounded;
private float LastShoot;
private int Health = 5;
public bool YaSono = false;
[Header("IFrame Stuff")]
public Color flashColor;
public Color regularColor;
public float flashDuration;
public int numberOfFlashes;
public Collider2D triggerCollider;
public SpriteRenderer mySprite;
float timer;
bool invencible = false;
private void Start()
{
Rigidbody2D = GetComponent<Rigidbody2D>();
Animator = GetComponent<Animator>();
}
// Update is called once per frame
private void Update()
{
timer -= Time.deltaTime;
if (timer <= 0)
{
invencible = false;
}
Horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
if (Horizontal < 0.0f) transform.localScale = new Vector3(-1.0f, 1.0f, 1.0f);
else if (Horizontal > 0.0f) transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
Animator.SetBool("Caminar", Horizontal != 0.0f);
Debug.DrawRay(transform.position, Vector3.down * 0.5f, Color.red);
if (Physics2D.Raycast(transform.position, Vector3.down, 0.5f))
{
Grounded = true;
}
else Grounded = false;
if (CrossPlatformInputManager.GetButtonDown("Jump") && Grounded)
{
Jump();
}
if (Input.GetKeyDown(KeyCode.W) && Grounded)
{
Jump();
}
if (Input.GetKey(KeyCode.Space) && Time.time > LastShoot + 0.25f)
{
Shoot();
LastShoot = Time.time;
}
if (CrossPlatformInputManager.GetButtonDown("Shoot") && Time.time > LastShoot + 0.50f)
{
Shoot();
LastShoot = Time.time;
}
/* if (CrossPlatformInputManager.GetButtonDown("Vertical") && Time.time > LastShoot + 0.50f)
{
Shoot();
LastShoot = Time.time;
}*/
if (transform.position.y <= -2)
{
Fall();
}
}
private void FixedUpdate()
{
Rigidbody2D.velocity = new Vector2(Horizontal * Speed, Rigidbody2D.velocity.y);
}
private void Jump()
{
Rigidbody2D.AddForce(Vector2.up * JumpForce);
Camera.main.GetComponent<AudioSource>().PlayOneShot(Salto);
}
private void Shoot()
{
Vector3 direction;
if (transform.localScale.x == 1.0f) direction = Vector3.right;
else direction = Vector3.left;
GameObject pastilla = Instantiate(PildoraPrefab, transform.position + direction * 0.40f, Quaternion.identity);
pastilla.GetComponent<Pastilla>().SetDirection(direction);
}
**public void Hit()
{
Health -= 1;
if (Health > 0)
{
StartCoroutine(FlashCo());
}
if (Health < 1)
{
Destroy(Corazones[0].gameObject);
}
else if (Health < 2)
{
Destroy(Corazones[1].gameObject);
}
else if (Health < 3)
{
Destroy(Corazones[2].gameObject);
}
else if (Health < 4)
{
Destroy(Corazones[3].gameObject);
}
else if (Health < 5)
{
Destroy(Corazones[4].gameObject);
}
if (Health > 0)
{
Camera.main.GetComponent<AudioSource>().PlayOneShot(Golpe);
}**
if (Health == 0)
{
Camera.main.GetComponent<AudioSource>().PlayOneShot(Muerte);
Animator.SetTrigger("Muerte");
if (Grounded == false)
{
Rigidbody2D.bodyType = RigidbodyType2D.Dynamic;
Rigidbody2D.gravityScale = 2;
}
else
{
Rigidbody2D.bodyType = RigidbodyType2D.Static;
}
}
}
public void Fall()
{
if (transform.position.y <= -1)
{
Rigidbody2D.AddForce(Vector2.up * 60);
if (!YaSono)
{
Camera.main.GetComponent<AudioSource>().PlayOneShot(Caida);
YaSono = true;
}
Animator.SetTrigger("Muerte");
Health = 0;
Destroy(Rigidbody2D, 2);
Destroy(Corazones[0].gameObject);
Destroy(Corazones[1].gameObject);
Destroy(Corazones[2].gameObject);
Destroy(Corazones[3].gameObject);
Destroy(Corazones[4].gameObject);
Invoke("RestartLevel", 2);
}
}
public void Vida()
{
if (Health >=5) { } else { Health += 1; }
}
public void Bounce()
{
Rigidbody2D.AddForce(Vector2.up * 300);
}
void Invencible()
{
timer = 1;
if (timer > 0)
{
invencible = true;
}
}
private IEnumerator FlashCo()
{
int temp = 0;
triggerCollider.enabled = false;
while (temp < numberOfFlashes)
{
mySprite.color = flashColor;
yield return new WaitForSeconds(flashDuration);
mySprite.color = regularColor;
yield return new WaitForSeconds(flashDuration);
temp++;
}
triggerCollider.enabled = true;
}
private void RestartLevel()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
Instead of using Destroy(Corazones[0].gameObject) you could use Corazones[0].gameObject.setActive(false) or simply Corazones[0].setActive(false) since the array already contains GameObjects.
This would preserve the GameObject while all of its components and children would be inactivated including its Renderer which would make it disappear.
Then later when you need it you could reactivate it using Corazones[0].setActive(true).

How do I call a method which is in another class, when swiping up, down, left or right? Unity2D

I have a Unity project that I started a couple of days ago. It is a simple 2D top down shooting game, which is aimed to be played on smartphone platforms.
I have a Shooting script, which basically has a method called Shoot1, which spawns in a bullet.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooting : MonoBehaviour
{
public Transform firePoint;
public GameObject BulletRedPrefab;
public GameObject BulletGreenPrefab;
public float bulletForce = 20f;
// Update is called once per frame
void Start()
{
}
void Update()
{
}
public IEnumerator Shoot1()
{
yield return new WaitForSeconds(0.00001f);
GameObject bullet = Instantiate(BulletRedPrefab, firePoint.position, firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
}
}
I also have the Swipe script which determines the direction of the swipe, etc.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Swipe : MonoBehaviour
{
private bool tap, swipeUp, swipeDown, swipeLeft, swipeRight;
private bool isDraging = false;
private Vector2 startTouch, swipeDelta;
// Update is called once per frame
private void Update()
{
tap = swipeUp = swipeDown = swipeLeft = swipeRight = false;
if (Input.touches.Length > 0)
{
if (Input.touches[0].phase == TouchPhase.Began)
{
isDraging = true;
tap = true;
startTouch = Input.touches[0].position;
}
else if (Input.touches[0].phase == TouchPhase.Ended || Input.touches[0].phase == TouchPhase.Canceled)
{
isDraging = false;
Reset();
}
}
if (Input.GetMouseButtonDown(0))
{
tap = true;
isDraging = true;
startTouch = Input.mousePosition;
}
else if (Input.GetMouseButtonUp(0))
{
isDraging = false;
Reset();
}
swipeDelta = Vector2.zero;
if (isDraging)
{
if (Input.touches.Length > 0)
swipeDelta = Input.touches[0].position - startTouch;
else if (Input.GetMouseButton(0))
swipeDelta = (Vector2)Input.mousePosition - startTouch;
}
if (swipeDelta.magnitude > 125)
{
float x = swipeDelta.x;
float y = swipeDelta.y;
if (Mathf.Abs(x) > Mathf.Abs(y))
{
if (x < 0)
swipeLeft = true;
else
swipeRight = true;
}
else
{
if (y < 0)
swipeDown = true;
else
swipeUp = true;
}
Reset();
}
}
private void Reset()
{
startTouch = swipeDelta = Vector2.zero;
isDraging = false;
}
public Vector2 SwipeDelta { get { return swipeDelta; } }
public bool SwipeUp { get { return swipeUp; } }
public bool SwipeDown { get { return swipeDown; } }
public bool SwipeLeft { get { return swipeLeft; } }
public bool SwipeRight { get { return swipeRight; } }
}
And I have the GestureDetector script which is aimed to shoot a bullet whenever the user swipes left, right, up or down. When I tried to make the player object (which is called robot) move via swiping, it worked. But when I try calling a method from another class with swiping, it's not working.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GestrueDetector : MonoBehaviour
{
public Shooting other;
public Swipe swipeControls;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
private void Update()
{
if (GameObject.Find("robot") != null)
{
if (swipeControls.SwipeLeft)
desirePosition += Vector3.left;
other.Shoot1();
if (swipeControls.SwipeRight)
desirePosition += Vector3.right;
other.Shoot1();
if (swipeControls.SwipeUp)
desirePosition += Vector3.up;
other.Shoot1();
if (swipeControls.SwipeDown)
desirePosition += Vector3.down;
other.Shoot1();
}
}
}
I just started using unity this week, so I'm quite new to the software. Thank you very much!
For coroutines you need to call this methods like this:
StartCoroutine(Shoot1());
I a little bit changed your classes:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooting : MonoBehaviour
{
public Transform firePoint;
public GameObject BulletRedPrefab;
public GameObject BulletGreenPrefab;
public float bulletForce = 20f;
void Start ()
{
}
void Update()
{
}
public void Shoot()
{
StartCoroutine(Shoot1());
}
private IEnumerator Shoot1()
{
yield return new WaitForSeconds(0.00001f);
GameObject bullet = Instantiate(BulletRedPrefab, firePoint.position, firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
}
}
And for GestrueDetector:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GestrueDetector : MonoBehaviour
{
public Shooting other;
public Swipe swipeControls;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
private void Update()
{
if (GameObject.Find("robot") != null)
{
if (swipeControls.SwipeLeft)
desirePosition += Vector3.left;
other.Shoot();
if (swipeControls.SwipeRight)
desirePosition += Vector3.right;
other.Shoot();
if (swipeControls.SwipeUp)
desirePosition += Vector3.up;
other.Shoot();
if (swipeControls.SwipeDown)
desirePosition += Vector3.down;
other.Shoot();
}
}
}
Just read more about how coroutines are working in Unity - https://docs.unity3d.com/ScriptReference/Coroutine.html

I have a working swipe detector script, but I don't know how to connect it to my character controller

My game is an endless runner and the character only needs to move along the y-axis. What I want to happen is that the player moves up or down depending on the swipe, and I thought that I could do it by stating that if the player triggered the onSwipeUp or down then they would move in that direction, but I couldn't get it working.
This is the player controller script before I tried implementing swipe controls into it:
public class Player : MonoBehaviour
{
private Vector2 targetPos;
public float yIncrement;
public float maxHeight;
public float minHeight;
private void Update()
{
transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.W) && transform.position.y < maxHeight)
{
Instantiate(effect, transform.position, Quaternion.identity);
targetPos = new Vector2(transform.position.x, transform.position.y + yIncrement);
}
else if (Input.GetKeyDown(KeyCode.S) && transform.position.y > minHeight)
{
Instantiate(effect, transform.position, Quaternion.identity);
targetPos = new Vector2(transform.position.x, transform.position.y - yIncrement);
}
}
And this is the swipe detecting script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwipeTest : MonoBehaviour
{
private Vector2 fingerDown;
private Vector2 fingerUp;
public bool detectSwipeOnlyAfterRelease = false;
public float SWIPE_THRESHOLD = 20f;
// Update is called once per frame
void Update()
{
foreach (Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
fingerUp = touch.position;
fingerDown = touch.position;
}
//Detects Swipe while finger is still moving
if (touch.phase == TouchPhase.Moved)
{
if (!detectSwipeOnlyAfterRelease)
{
fingerDown = touch.position;
checkSwipe();
}
}
//Detects swipe after finger is released
if (touch.phase == TouchPhase.Ended)
{
fingerDown = touch.position;
checkSwipe();
}
}
}
void checkSwipe()
{
//Check if Vertical swipe
if (verticalMove() > SWIPE_THRESHOLD && verticalMove() > horizontalValMove())
{
//Debug.Log("Vertical");
if (fingerDown.y - fingerUp.y > 0)//up swipe
{
OnSwipeUp();
}
else if (fingerDown.y - fingerUp.y < 0)//Down swipe
{
OnSwipeDown();
}
fingerUp = fingerDown;
}
//Check if Horizontal swipe
else if (horizontalValMove() > SWIPE_THRESHOLD && horizontalValMove() > verticalMove())
{
//Debug.Log("Horizontal");
if (fingerDown.x - fingerUp.x > 0)//Right swipe
{
OnSwipeRight();
}
else if (fingerDown.x - fingerUp.x < 0)//Left swipe
{
OnSwipeLeft();
}
fingerUp = fingerDown;
}
//No Movement at-all
else
{
//Debug.Log("No Swipe!");
}
}
float verticalMove()
{
return Mathf.Abs(fingerDown.y - fingerUp.y);
}
float horizontalValMove()
{
return Mathf.Abs(fingerDown.x - fingerUp.x);
}
//////////////////////////////////CALLBACK FUNCTIONS/////////////////////////////
public void OnSwipeUp()
{
Debug.Log("Swipe UP");
}
public void OnSwipeDown()
{
Debug.Log("Swipe Down");
}
void OnSwipeLeft()
{
Debug.Log("Swipe Left");
}
void OnSwipeRight()
{
Debug.Log("Swipe Right");
}
}
You could set a public boolean for each swipe direction. In the first lines of update set these booleans to false, in the onswipe functions set the respective booleans to true. Then reference the swipetest script from the player script and check if the desired swipe boolean is set to true.
The code would look something like this:
player:
public class Player : MonoBehaviour
{
private Vector2 targetPos;
public float yIncrement;
public float maxHeight;
public float minHeight;
public SwipeTest swipetest;
private void OnEnable()
{
swipetest = (SwipeTest)FindObjectOfType(typeof(SwipeTest));
}
private void Update()
{
transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
if (swipetest.swipeUp && transform.position.y < maxHeight)
{
Instantiate(effect, transform.position, Quaternion.identity);
targetPos = new Vector2(transform.position.x, transform.position.y + yIncrement);
}
else if (swipetest.swipeDown && transform.position.y > minHeight)
{
Instantiate(effect, transform.position, Quaternion.identity);
targetPos = new Vector2(transform.position.x, transform.position.y - yIncrement);
}
}
swipetest
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwipeTest : MonoBehaviour
{
private Vector2 fingerDown;
private Vector2 fingerUp;
public bool detectSwipeOnlyAfterRelease = false;
public float SWIPE_THRESHOLD = 20f;
public bool swipeUp = false;
public bool swipeDown = false;
public bool swipeLeft = false;
public bool swipeRight = false;
// Update is called once per frame
void Update()
{
swipeUp = false;
swipeDown = false;
swipeLeft = false;
swipeRight = false;
foreach (Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
fingerUp = touch.position;
fingerDown = touch.position;
}
//Detects Swipe while finger is still moving
if (touch.phase == TouchPhase.Moved)
{
if (!detectSwipeOnlyAfterRelease)
{
fingerDown = touch.position;
checkSwipe();
}
}
//Detects swipe after finger is released
if (touch.phase == TouchPhase.Ended)
{
fingerDown = touch.position;
checkSwipe();
}
}
}
void checkSwipe()
{
//Check if Vertical swipe
if (verticalMove() > SWIPE_THRESHOLD && verticalMove() > horizontalValMove())
{
//Debug.Log("Vertical");
if (fingerDown.y - fingerUp.y > 0)//up swipe
{
OnSwipeUp();
}
else if (fingerDown.y - fingerUp.y < 0)//Down swipe
{
OnSwipeDown();
}
fingerUp = fingerDown;
}
//Check if Horizontal swipe
else if (horizontalValMove() > SWIPE_THRESHOLD && horizontalValMove() > verticalMove())
{
//Debug.Log("Horizontal");
if (fingerDown.x - fingerUp.x > 0)//Right swipe
{
OnSwipeRight();
}
else if (fingerDown.x - fingerUp.x < 0)//Left swipe
{
OnSwipeLeft();
}
fingerUp = fingerDown;
}
//No Movement at-all
else
{
//Debug.Log("No Swipe!");
}
}
float verticalMove()
{
return Mathf.Abs(fingerDown.y - fingerUp.y);
}
float horizontalValMove()
{
return Mathf.Abs(fingerDown.x - fingerUp.x);
}
//////////////////////////////////CALLBACK FUNCTIONS/////////////////////////////
public void OnSwipeUp()
{
swipeUp = true;
}
public void OnSwipeDown()
{
swipeDown = true;
}
void OnSwipeLeft()
{
swipeLeft = true;
}
void OnSwipeRight()
{
swipeRight = true;
}
}

Unity | When swipe left trigger button click

I'm developing a mobile android game in Unity, and I have a menu panel that slides in from the right, using animation, when a button is clicked. Now I want to trigger the button to be clicked when the player swipes left. Basically I want to "click the menu button" when I swipe left on the screen without actually touching the button. This way it would trigger the animation and all other function of the button. Is it possible to achieve that? This is my script for the swipe detection:
//Swipe
private bool tap, swipeLeft, swipeRight, swipeUp, swipeDown;
private bool isDraging = false;
private Vector2 startTouch, swipeDelta;
private void Update()
{
tap = swipeLeft = swipeRight = swipeUp = swipeDown = false;
if (Input.touches.Length > 0)
{
if (Input.touches[0].phase == TouchPhase.Began)
{
isDraging = true;
tap = true;
startTouch = Input.touches[0].position;
}
else if (Input.touches[0].phase == TouchPhase.Ended || Input.touches[0].phase == TouchPhase.Canceled)
{
isDraging = false;
Reset();
}
}
//Calculate Distance
swipeDelta = Vector2.zero;
if (isDraging)
{
if (Input.touches.Length > 0)
{
swipeDelta = Input.touches[0].position - startTouch;
}
}
if (swipeDelta.magnitude > 125)
{
float x = swipeDelta.x;
float y = swipeDelta.y;
if (Mathf.Abs(x) > Mathf.Abs(y))
{
//Left Or Right
if (x < 0)
{
swipeLeft = true;
}
else
{
swipeRight = true;
}
}
else
{
if (y < 0)
{
swipeDown = true;
}
else
{
swipeUp = true;
}
}
Reset();
}
}
private void Reset()
{
startTouch = Vector2.zero;
isDraging = false;
}
public Vector2 SwipeDelta { get { return swipeDelta; } }
public bool SwipeLeft { get { return swipeLeft; } }
public bool SwipeRight { get { return swipeRight; } }
public bool SwipeUp { get { return swipeUp; } }
public bool SwipeDown { get { return swipeDown; } }
How can I achieve my idea and how to implement it to my game?

Categories

Resources