I wanted to make that when you swipe to the left you apply a left force and when you swipe to the right you apply a right force.
this is how I imagine the code would be:
private Vector2 direction;
void Update()
{
swipeDirection();
}
void FixedUpdate()
{
rb2D.AddForce(direction);
}
void swipeDirection()
{
if (swipe to the left)
{
direction = new Vector2(-10, 0);
}
else if (swipe to the right)
{
direction = new Vector2(10, 0);
}
}
CodePudding user response:
I would try something like this:
using UnityEngine;
public class ApplyForceOnSwipe: MonoBehaviour {
Vector3 touchInitPos;
Vector3 touchEndPos;
bool applyForce = false;
Vector3 forceDir;
void Update() {
if (Input.GetTouch(0).phase == TouchPhase.Began) {
touchInitPos = Input.GetTouch(0).position;
}
if (Input.GetTouch(0).phase == TouchPhase.Ended) {
touchEndPos = Input.GetTouch(0).position;
forceDir = (touchEndPos - touchInitPos).normalized;
applyForce = true;
}
}
void FixedUpdate() {
if (applyForce) {
rb2D.AddForce(forceDir);
applyForce = false;
}
}
}
Used a boolean to avoid applying the force multiple times and apply it only once per swipe. Not debuggued. Hope it might work or inspire you :)
