I need help with (what I believe to be simple but I don’t know) something (for android):
I have a 2D ball, that is on a simple square table, I want to drag from that ball and release and upon release the ball goes in that direction or in opposite direction if you drag “behind” the ball. I don’t need aim, or arrows or anything. Just put your finger on the ball then drag and release. I searched for 2 days on forums and youtube and everywhere but I couldn’t find what I need. I found something but it’s really outdated and does not help me.
Thank you for your help! And I am sorry for taking your time if there is already something answered that I didn’t find!
EDIT: THE RIGHT CODE IS NOW POSTED
I found it, hope this helps someone else too!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Swipe : MonoBehaviour {
Rigidbody2D rbody;
Vector2 startpos;
Vector2 endpos;
float power = 5f; // power of shot
// Use this for initialization
void Start () {
rbody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonUp(0))
{
endpos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
LaunchBall();
}
}
}
void OnMouseDown()
{
startpos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
void LaunchBall()
{
Vector2 direction = (startpos - endpos); // swap subtraction to switch direction of launch
rbody.AddForce(direction * power, ForceMode2D.Impulse);
}
How can i use it with touch controls not mouse input ?