Right now I've been developing a game which will make the character move up or down if either swipe up or down on the left side of the screen. Then, he can also, shoot projectiles if I tap the right side of the screen. I've succeeded on making it work but the problem is that the swipe function do not works while I tap the the right screen. Both only works if I do one of them. I cannot move the character if I am firing projectiles. Any suggestions? Appreciate it in advanced.
Here's the code:
For the swipe movement function:
void Swipe() {
if (Input.touchCount > 0) {
Touch t = Input.GetTouch(0);
if (t.phase == TouchPhase.Began)
{
lp = t.position;
fp = t.position;
text.text = fp.x.ToString();
}
else if (t.phase == TouchPhase.Ended)
{
lp = t.position;
//Swipe Up
if (fp.y < lp.y && fp.x < 400)
{
currentLane += 1;
}
//Swipe Down
else if (fp.y > lp.y && fp.x < 400)
{
currentLane -= 1;
}
}
}
}
And here's the code for the tap or firing projectiles function:
void FireBullets() {
interval += 2 * Time.deltaTime;
anim.SetBool("Attacking", firing);
if (Input.touchCount > 0 && interval > .75f) {
Vector3 bulletTouchPos;
Touch bulletT = Input.GetTouch(0);
bulletTouchPos = bulletT.position;
if (bulletT.phase == TouchPhase.Began) {
if (bulletTouchPos.x > 400)
{
interval = 0;
firing = true;
//Fire Bullets
Instantiate(bullets, new Vector3(transform.position.x + 1.2f, transform.position.y + .3f, transform.position.z), Quaternion.identity);
}
}
}else
{
firing = false;
}
}
Your lp and fp values don't care which finger is being checked.
If you want to detect multiple touch gestures at once, you need to discriminate your detection based on which finger that is.
You can do this by looking at the Touch.fingerId value, which is unique for each finger. Fingers are just an ID assigned to a given touching point as it moves across the screen in order to identify it from other touching points currently also on the screen.
You'll need to adjust your code to handle how to store the information you need in order to do what you need, but this should get you started.
Related
I'm creating an Android game with Unity. There are only three ways to control the movement of the character:
Tap in the right half of the screen: jump to the right
Tap in the left half of the screen: jump to the left
Swipe upwards: character dashes forward
In theory, I know that I can differentiate the touches with the TouchPhases (began, moved, stationary and ended). When only detecting the taps without caring for swipes, I just checked if the phase of the touch began and made the player jump. That felt fast on my device.
However, because I have to consider that a swipe may follow, I can not initiate the jump action until I detected ThouchPhase.Ended. This leads to a very slow responding character, which doesnt jump until the user rises his finger of the screen.
I tried to use ThouchPhase.Moved and ThouchPhase.Stationary instead to simulate a immediate response but my solution is pretty bad in terms of detecting the difference between a tap and a swipe:
Vector2 startTouchPosition;
Vector2 endTouchPosition;
Vector2 currentSwipe;
void Update()
{
if (Input.touches.Length > 0)
{
for (int i = 0; i < Input.touchCount; i++)
{
Touch touch = Input.GetTouch(i);
if (touch.phase == TouchPhase.Began)
{
//save began touch 2d point
startTouchPosition = new Vector2(touch.position.x, touch.position.y);
}
if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary)
{
//save ended touch 2d point
endTouchPosition = new Vector2(touch.position.x, touch.position.y);
if (endTouchPosition.y - startTouchPosition.y < 5)
{
if (touch.position.x > (Screen.width / 2))
{
JumpToRight();
}
else if (touch.position.x < (Screen.width / 2))
{
JumpToLeft();
}
}
else
{
//create vector from the two points
currentSwipe = new Vector2(endTouchPosition.x - startTouchPosition.x, endTouchPosition.y - startTouchPosition.y);
//normalize the 2d vector
currentSwipe.Normalize();
//swipe upwards
if (currentSwipe.y > 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f)
{
DashForward();
}
}
}
}
}
}
Here is the code I used. I tested and it works but sometimes, I noted a delay. Let me know if it is good enough for you. Basically you dont need to go through all touches if you dont need multi-touch. And you just need Begin and End touch phases.
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class touch : MonoBehaviour {
private Vector2 startTouchPosition;
private Vector2 endTouchPosition;
private Vector2 currentSwipe;
public Text textbox;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.touches.Length > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
//save began touch 2d point
startTouchPosition = new Vector2(touch.position.x, touch.position.y);
}
if (touch.phase == TouchPhase.Ended)
{
//save ended touch 2d point
endTouchPosition = new Vector2(touch.position.x, touch.position.y);
//create vector from the two points
currentSwipe = new Vector2(endTouchPosition.x - startTouchPosition.x, endTouchPosition.y - startTouchPosition.y);
//normalize the 2d vector
currentSwipe.Normalize();
if(Mathf.Abs(currentSwipe.y) < 0.1f && Mathf.Abs(currentSwipe.x) < 0.1f)
{
if (touch.position.x > (Screen.width / 2))
{
textbox.text= "jump right";
}
else if (touch.position.x < (Screen.width / 2))
{
textbox.text= "jump left";
}
}
if (currentSwipe.y > 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f)
{
textbox.text= "Dash forward";
}
}
}
}
}
I'm doing a game to android with Unity and I don't know how to do to jump more or less depending how much time you press the screen, I tried it but I don't know how to do it, I used deltatime but it doesn't work, at least no at least not in the way I did it, so I would like to know how to do that. The character jumps but just a little bit, it doesn't matter how much time I press the screen, it jumps so low.
This is how I've tried to accomplish that:
void Update () {
movimiento ();
if (transform.position.x <= 4.65f) {
SceneManager.LoadScene ("Game Over");
}
if (Input.touchCount > 0) {
GetComponent<Animator> ().Play ("Andar 2");
print (Input.GetTouch (0).deltaTime);
if (Input.GetTouch (0).deltaTime >= 2) {
GetComponent<Rigidbody2D> ().AddForce (Vector3.up * Time.deltaTime * 20000);
GetComponent<Animator> ().Play ("Andar 2");
} else if (Input.GetTouch (0).deltaTime >= 1) {
GetComponent<Rigidbody2D> ().AddForce (Vector3.up * Time.deltaTime * 2000);
} else if (Input.GetTouch (0).deltaTime < 1) {
GetComponent<Rigidbody2D> ().AddForce (Vector3.up * Time.deltaTime * 200);
}
}
}
I like to work with velocities directly when doing jumps as i feel like i can be more precise with it, But regardless, here is my solution for variable height jumps.
void Update ()
{
// set jump controls
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
jump = true;
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended && !grounded)
jumpCancel = true;
}
void FixedUpdate()
{
// if player presses jump
if (jump)
{
rigidbody.velocity = new Vector3(rigidbody.velocity.x, jumpVelocity, rigidbody.velocity.z);
jump = false;
}
// if player performes a jump cancel
if (jumpCancel)
{
if (rigidbody.velocity.y > shortJumpVelocity)
rigidbody.velocity = new Vector3(rigidbody.velocity.x, shortJumpVelocity, rigidbody.velocity.z);
controller.jumpCancel = false;
}
}
This works by altering the player's velocity if the finger is lifted before the shortJumpVelocity is reached. As you can see you will have to have a grounded state of some kind for this to work properly.
I love this method as it avoids timers and gives the player a lot of control.
I wanted to make a little game with touch inputs and this is the code I made for it: (This is inside the Update method)
//Check if Input has registered more than zero touches
if(Input.touchCount > 0){
//Store the first touch detected.
Touch myTouch = Input.touches[0];
//Check if the phase of that touch equals Began
if (myTouch.phase == TouchPhase.Began)
{
//If so, set touchOrigin to the position of that touch
touchOrigin = myTouch.position;
if(touchOrigin.x < -2){
horizontalInput = -1;
} else if(touchOrigin.x > 2){
horizontalInput = 1;
}
if(touchOrigin.x > -2 && touchOrigin.x < 2 && touchOrigin.y < 0){
verticalInput = 1;
}
} else if(myTouch.phase == TouchPhase.Ended){
horizontalInput = 0;
verticalInput = 0;
}
}
This is my scene: http://i.stack.imgur.com/PGbd3.jpg
When I tried it on my android phone it only moved to the right and I don't know why.
(My camera's position is: x: -6,6; y:-2,6) And I'm using an orthographic camera
This is becase you're using Touch.position, which returns values based on SCREEN space, rather than WORLD space.
What you need to do is convert the point from Screen to World space before applying your conditions. You can do that by using Camera.ScreenToWorldPoint.
I'm trying to get unity to recognize that I am swiping left to right, I have solved that but my issue is that it doesn't understand this till I lift my finger off the screen.
My question is how would i make it so that it knows i went right and then left and then right again all without ever taking my finger of the screen
Here is the code I have so far
using UnityEngine;
using System.Collections;
public class Gestures : MonoBehaviour {
private Vector2 fingerStart;
private Vector2 fingerEnd;
public int leftRight = 0;
public int upDown = 0;
void Update () {
foreach(Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
fingerStart = touch.position;
fingerEnd = touch.position;
}
if (touch.phase == TouchPhase.Moved )
{
fingerEnd = touch.position;
}
if(touch.phase == TouchPhase.Ended)
{
if((fingerStart.x - fingerEnd.x) > 80 || (fingerStart.x - fingerEnd.x) < -80) // Side to side Swipe
{
leftRight ++;
}
else if((fingerStart.y - fingerEnd.y) < -80 || (fingerStart.y - fingerEnd.y) > 80) // top to bottom swipe
{
upDown ++;
}
if(leftRight >= 3){
leftRight = 0;
}
if(upDown >= 4){
upDown = 0;
}
}
}
}
}
The issue you're facing is because you've done your checks in the TouchPhase.Ended. What you want to do is perform your checks in TouchPhase.Moved, with a smaller change in value (you're using 80 in Ended, try something like 10 if you the code doesn't work)
Unity's documentation on TouchPhase http://docs.unity3d.com/ScriptReference/TouchPhase.html
foreach(Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
fingerStart = touch.position;
fingerEnd = touch.position;
}
if (touch.phase == TouchPhase.Moved )
{
fingerEnd = touch.position;
if((fingerStart.x - fingerEnd.x) > 80 ||
(fingerStart.x - fingerEnd.x) < -80) // Side to side Swipe
{
leftRight ++;
}
else if((fingerStart.y - fingerEnd.y) < -80 ||
(fingerStart.y - fingerEnd.y) > 80) // top to bottom swipe
{
upDown ++;
}
if(leftRight >= 3){
leftRight = 0;
}
if(upDown >= 4){
upDown = 0;
}
//After the checks are performed, set the fingerStart & fingerEnd to be the same
fingerStart = touch.position;
}
if(touch.phase == TouchPhase.Ended)
{
leftRight = 0;
upDown = 0;
fingerStart = Vector2.zero;
fingerEnd = Vector2.zero;
}
If you want to explicitly check for a pattern (i.e. left -> right -> left), rather than just checking if it's some lateral / vertical movement as the code you have will do, try the below code. Just remember to include System.Collentions.Generic & System.Linq namespaces
private Vector2 fingerStart;
private Vector2 fingerEnd;
public enum Movement
{
Left,
Right,
Up,
Down
};
public List<Movement> movements = new List<Movement>();
void Update () {
foreach(Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began) {
fingerStart = touch.position;
fingerEnd = touch.position;
}
if(touch.phase == TouchPhase.Moved) {
fingerEnd = touch.position;
//There is more movement on the X axis than the Y axis
if(Mathf.Abs(fingerStart.x - fingerEnd.x) > Mathf.Abs(fingerStart.y - fingerEnd.y)) {
//Right Swipe
if((fingerEnd.x - fingerStart.x) > 0)
movements.Add(Movement.Right);
//Left Swipe
else
movements.Add(Movement.Left);
}
//More movement along the Y axis than the X axis
else {
//Upward Swipe
if((fingerEnd.y - fingerStart.y) > 0)
movements.Add(Movement.Up);
//Downward Swipe
else
movements.Add(Movement.Down);
}
//After the checks are performed, set the fingerStart & fingerEnd to be the same
fingerStart = touch.position;
//Now let's check if the Movement pattern is what we want
//In this example, I'm checking whether the pattern is Left, then Right, then Left again
Debug.Log (CheckForPatternMove(0, 3, new List<Movement>() { Movement.Left, Movement.Right, Movement.Left } ));
}
if(touch.phase == TouchPhase.Ended)
{
fingerStart = Vector2.zero;
fingerEnd = Vector2.zero;
movements.Clear();
}
}
}
private bool CheckForPatternMove (int startIndex, int lengthOfPattern, List<Movement> movementToCheck) {
//If the currently stored movements are fewer than the length of the pattern to be detected
//it can never match the pattern. So, let's get out
if(lengthOfPattern > movements.Count)
return false;
//In case the start index for the check plus the length of the pattern
//exceeds the movement list's count, it'll throw an exception, so lets get out
if(startIndex + lengthOfPattern > movements.Count)
return false;
//Populate a temporary list with the respective elements
//from the movement list
List<Movement> tMovements = new List<Movement>();
for(int i = startIndex; i < startIndex + lengthOfPattern; i++)
tMovements.Add(movements[i]);
//Now check whether the sequence of movements is the same as the pattern you want to check for
//The SequenceEqual method is in the System.Linq namespace
return tMovements.SequenceEqual(movementToCheck);
}
EDIT Added some more code as a sample
//The idea of a pattern match is to check for the exact same set of swipe gesture.
//This requires the following conditions to be met
// (a) The List of movements that need to be checked must be at least as long as the List of movements to check against.
// (b) The correct indices should be used for the startIndex. In this case I'm just using 0 as the startIndex.
// (c) Remember to clear the List right after you get a true return from the method, otherwise the next return will most likely be a false.
//Example - Training set is Left -> Right -> Left (This is what we want to check)
// Step 1 - User swipes LEFT, method returns false because there are too few Movements to check
// Step 2 - User swipes RIGHT, method returns false (same reason as above)
// Step 3a - User swipes RIGHT (L, R, R now) - false, incorrect pattern (L, R, R instead of L, R, L)
// Step 3b - User swipes LEFT (L, R, L now) - TRUE, Correct pattern!
//Immediately clear if Step 3b happens otherwise Step 4 will occur
// Step 4 - User swipes L or R (direction is immaterial right now), and method will return FALSE
// if you use the last three indexes!
//Pre-populating the movements List with L, R, L
movements = new List<Movement>()
{
Movement.Left,
Movement.Right,
Movement.Left
};
//Checking a match against an L, R, L training set
//This prints true to the console
Debug.Log (CheckForPatternMove(0, 3, new List<Movement>() { Movement.Left, Movement.Right, Movement.Left } ));
Here's how my Update function looks like. Note the usage of GetMouseButton over Input.touch
void Update () {
//Example usage in Update. Note how I use Input.GetMouseButton instead of Input.touch
//GetMouseButtonDown(0) instead of TouchPhase.Began
if (Input.GetMouseButtonDown(0)) {
fingerStart = Input.mousePosition;
fingerEnd = Input.mousePosition;
}
//GetMouseButton instead of TouchPhase.Moved
//This returns true if the LMB is held down in standalone OR
//there is a single finger touch on a mobile device
if(Input.GetMouseButton(0)) {
fingerEnd = Input.mousePosition;
//There was some movement! The tolerance variable is to detect some useful movement
//i.e. an actual swipe rather than some jitter. This is the same as the value of 80
//you used in your original code.
if(Mathf.Abs(fingerEnd.x - fingerStart.x) > tolerance ||
Mathf.Abs(fingerEnd.y - fingerStart.y) > tolerance) {
//There is more movement on the X axis than the Y axis
if(Mathf.Abs(fingerStart.x - fingerEnd.x) > Mathf.Abs(fingerStart.y - fingerEnd.y)) {
//Right Swipe
if((fingerEnd.x - fingerStart.x) > 0)
movements.Add(Movement.Right);
//Left Swipe
else
movements.Add(Movement.Left);
}
//More movement along the Y axis than the X axis
else {
//Upward Swipe
if((fingerEnd.y - fingerStart.y) > 0)
movements.Add(Movement.Up);
//Downward Swipe
else
movements.Add(Movement.Down);
}
//After the checks are performed, set the fingerStart & fingerEnd to be the same
fingerStart = fingerEnd;
//Now let's check if the Movement pattern is what we want
//In this example, I'm checking whether the pattern is Left, then Right, then Left again
Debug.Log (CheckForPatternMove(0, 3, new List<Movement>() { Movement.Left, Movement.Right, Movement.Left } ));
}
}
//GetMouseButtonUp(0) instead of TouchPhase.Ended
if(Input.GetMouseButtonUp(0)) {
fingerStart = Vector2.zero;
fingerEnd = Vector2.zero;
movements.Clear();
}
}
Can anyone help please.
Im writing a small Android game where the player is able to select a "barrier" and drag it accross the screen with their finger. I have the barriers drawn on the screen and I am able to drag it accross the screen.
My problem however is when I add more than 1 barrier, eg 3 barriers, and drag a barrier accross the screen, they all drag and they all drag to the same position. That is to say they all lie on top of each other, making it look as though there is only 1 barrier.
Here is my code, can anyone please tell me where I am going wrong/explain where I am going wrong.
public class MainGamePanel extends SurfaceView implements SurfaceHolder.Callback, SensorEventListener {
// Initialising the Barrier
private Barrier barrier[] = new Barrier[3];
// The Main Game Panel
public MainGamePanel(Context context) {
super(context);
// Adding a call-back (this) to the surfaceHolder to intercept events
getHolder().addCallback(this);
// Creating the Game items
// The starting coordinates of the Barrier
int x = 30;
int y = 270;
barrier[0] = new Barrier(BitmapFactory.decodeResource(getResources(), R.drawable.blue_barrier), x, y);
barrier[1] = new Barrier(BitmapFactory.decodeResource(getResources(), R.drawable.green_barrier), x + 15, y);
barrier[2] = new Barrier(BitmapFactory.decodeResource(getResources(), R.drawable.pink_barrier), x + 30, y);
// Create the Game Loop Thread
thread = new MainThread(getHolder(), this);
// Make the GamePanel focusable so it can handle events
setFocusable(true);
}
// Handles the touch events
public boolean onTouchEvent(MotionEvent event)
{
int eventAction = event.getAction();
int x = (int)event.getX();
int y = (int)event.getY();
switch (eventAction)
{
// Touch down so check if finger is on Barrier
case MotionEvent.ACTION_DOWN:
if (x > barrier[0].getX() && x < barrier[0].getX() + 8
&& y > barrier[0].getX() && y < barrier[0].getY() + 8)
{
barrier[0].isTouched();
}
else if (x > barrier[1].getX() && x < barrier[1].getX() + 8
&& y > barrier[1].getX() && y < barrier[1].getY() + 8)
{
barrier[1].isTouched();
}
else if (x > barrier[2].getX() && x < barrier[2].getX() + 8
&& y > barrier[2].getX() && y < barrier[2].getY() + 8)
{
barrier[2].isTouched();
}
break;
// Touch-drag with the Barrier
case MotionEvent.ACTION_MOVE:
// Move the Barrier the same as the finger
for (int i = 0; i < barrier.length; i++)
{
if (barrier[i] == barrier[0])
{
barrier[0].setX(x);
barrier[0].setY(y);
} // end if
else if (barrier[i] == barrier[1])
{
barrier[1].setX(x);
barrier[1].setY(y);
}
else if (barrier[i] == barrier[2])
{
barrier[2].setX(x);
barrier[2].setY(y);
} // end else if
} // end for
break;
case MotionEvent.ACTION_UP:
// Finger no longer on Barrier - Do Nothing
break;
}
return true;
}
// Render - Draws the Game Item Bitmaps to the screen
public void render(Canvas canvas)
{
// Set the background to white
canvas.drawColor(Color.WHITE);
barrier[0].draw(canvas);
barrier[1].draw(canvas);
barrier[2].draw(canvas);
}
// Update
// This is the Game's update method
// It iterates through all the Objects and calls their update() methods (if they have one)
public void update()
{
} // end update
In your barrier move code, you aren't checking a particular barrier is touched, so you're moving all of them to the same coordinates. The following loop does exactly the same thing as your current code:
// Move the Barrier the same as the finger
for (int i = 0; i < barrier.length; i++)
{
barrier[i].setX(x);
barrier[i].setY(y);
} //end for
To fix this, you need to check if the current barrier in the loop is the one that was touched, and can change that whole loop to something like:
// Move the Barrier the same as the finger
for (int i = 0; i < barrier.length; i++)
{
if (barrier[i].isTouched())
{
barrier[i].setX(x);
barrier[i].setY(y);
} // end if
} // end for
You would then need to make sure that you un-set the touched property in the ACTION_UP section. If you post your Barrier class definition I can probably help more.
I'm pretty sure your problem could be solved by making the barriers three separate objects instead of in an array.
As already pointed out, your code in handling the move is wrong because it moves all the Barriers to the same X,Y when it should only move the one that is touched.
Also, you are never resetting the isTouched on the objects in the Action up. When the user lifts their finger you should set them all to isTouched == false. If you don't do that then once you touch one it will always move to the X,Y.