- Home /
Rotate gameObject with touch controls OR gameObject follow finger
I am making a simple and my first 2d game like super hexagon.. I just made it for windows but I want to make it for android but I don't know how to control player with touch in android. Do someone have any solution?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Player : MonoBehaviour {
public float moveSpeed = 600f;
float movement = 0f;
// Update is called once per frame
void Update () {
movement = Input.GetAxisRaw("Horizontal");
}
private void FixedUpdate() {
transform.RotateAround(Vector3.zero, Vector3.forward, movement * Time.fixedDeltaTime * -moveSpeed);
}
private void OnTriggerEnter2D(Collider2D collision) {
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
Answer by Vipers · Dec 03, 2018 at 02:52 PM
Hey, how are you? Super Hexagon has a kind of "locked" player that only moves by rotating itself, and I honestly don't like it that way, I prefer it to be freely moved, so the Player script for touch only should be like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Player : MonoBehaviour {
//determines the player speed
public float moveSpeed;
// Update is called once per frame
void Update ()
{
//touch screen movement
if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved){
Vector2 TouchPosition = Input.GetTouch(0).deltaPosition;
transform.Translate(TouchPosition.x * moveSpeed * Time.deltaTime, TouchPosition.y * moveSpeed * Time.deltaTime, 0);
}
}
}
Here, moveSpeed is a float that determines the player speed, a value around 5 should be fine (it's customizable on "Inspector" panel.
Also, you should create a new script for your player, to define screen size limits, I called mine "ScreenLimits", and used Mathf.Clamp for it, see below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScreenLimits : MonoBehaviour {
void Update() {
//the values of X and Y are customizable as the screen size of your mobile device
transform.position = new Vector3(Mathf.Clamp(transform.position.x, -7.7f, 7.7f),
Mathf.Clamp(transform.position.y, -14f, 14f), transform.position.z);
}
}
As I put in the script, the value of X and Y are from your mobile screen size, so it can change according to your preferences.
Hope it helps you!