Skip to content

Instantly share code, notes, and snippets.

@TortleWortle
Created August 11, 2016 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TortleWortle/b021cffb1f0e2584bf5c91062ce4f7ab to your computer and use it in GitHub Desktop.
Save TortleWortle/b021cffb1f0e2584bf5c91062ce4f7ab to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
public class PlayerMovements : MonoBehaviour{
// Normal Movements Variables
public float walkSpeed = 5f;
private float currentSpeed;
private Rigidbody2D rb2d;
public float touchRadius = 10;
public float maxTouchRadius = 90;
private bool fingerPlaced;
private Vector3 placedPos;
private Vector3 pos;
private Vector3 dist;
private Vector2 newVel;
private bool shouldMove = false;
private bool movingHorizontal = true;
void Awake() {
Application.targetFrameRate = 25;
}
void Start()
{
rb2d = GetComponent<Rigidbody2D> ();
}
void Update(){
if (Input.GetMouseButtonDown(0) && !fingerPlaced) {
fingerPlaced = true;
placedPos = Input.mousePosition;
pos = placedPos;
}
if (fingerPlaced) {
newVel = Vector2.zero;
pos = Input.mousePosition;
dist = placedPos - pos;
dist.x = -Mathf.Clamp (dist.x, -maxTouchRadius, maxTouchRadius) / maxTouchRadius;
dist.y = -Mathf.Clamp (dist.y, -maxTouchRadius, maxTouchRadius) / maxTouchRadius;
if ((dist.x * maxTouchRadius >= touchRadius) || (dist.x * maxTouchRadius <= -touchRadius)) {
movingHorizontal = true;
if (dist.x > 0) {
newVel.x = dist.x * walkSpeed;
}else if(dist.x < 0) {
newVel.x = dist.x * walkSpeed;
}
}
if ((dist.y * maxTouchRadius >= touchRadius) || (dist.y * maxTouchRadius <= -touchRadius)) {
//move Y pos
movingHorizontal = false;
if (dist.y > 0) {
newVel.y = dist.y * walkSpeed;
}else if(dist.y < 0) {
newVel.y = dist.y * walkSpeed;
}
}
rb2d.velocity = newVel;
}
if (Input.GetMouseButtonUp(0)) {
//cleanup
fingerPlaced = false;
placedPos = new Vector3();
rb2d.velocity = new Vector2 ();
}
if (fingerPlaced) {
if (movingHorizontal) {
rb2d.velocity = new Vector2(newVel.x, 0.0f);
} else {
rb2d.velocity = new Vector2(0.0f, newVel.y);
}
}
}
void FixedUpdate()
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment