Hi guys,
I’m trying to implement simple buttons to move my 2D character around the screen, and make him able to use any of the available functions in my PlayerControl script. I have my keyboard controls all set and done, but I don’t know how to implement some touch features. I have some GUITexture GameObjects set up, however, I don’t know how to hook up the code so that the touch buttons may communicate with my PlayerControl script.
How may I achieve this?
This is what my PlayerControl script looks like:
using UnityEngine;
using System.Collections;
public class PlayerControl : MonoBehaviour
{
public float moveSpeed = 4f;
public float jumpSpeed = 200f;
public bool grounded, interact = false;
public Transform lineStart, lineEnd, groundedEnd, destination;
float jumpTime, jumpDelay = .5f;
bool jumped;
Animator anim;
RaycastHit2D interaction;
void Start ()
{
anim = GetComponent<Animator> ();
}
// Update is called once per frame
void Update ()
{
Movement ();
Raycasting ();
}
// Movement script
void Movement ()
{
anim.SetFloat ("speed", Mathf.Abs (Input.GetAxis ("Horizontal")));
anim.SetFloat ("falling", Mathf.Abs (rigidbody2D.velocity.y));
//move right
if (Input.GetAxisRaw ("Horizontal") > 0) {
transform.Translate (Vector2.right * moveSpeed * Time.deltaTime);
transform.eulerAngles = new Vector2 (0, 0); //rotate character
}
//move left
if (Input.GetAxisRaw ("Horizontal") < 0) {
transform.Translate (Vector2.right * moveSpeed * Time.deltaTime);
transform.eulerAngles = new Vector2 (0, 180); //rotate character
}
//jump if grounded
if (Input.GetKeyDown (KeyCode.Space) && grounded == true) {
rigidbody2D.AddForce (Vector2.up * jumpSpeed);
jumpTime = jumpDelay;
anim.SetTrigger ("jump");
jumped = true;
}
jumpTime -= Time.deltaTime;
if (jumpTime <= 0 && grounded && jumped) {
anim.SetTrigger ("landing");
jumped = false;
anim.SetTrigger ("ground");
}
if (Input.GetKeyDown (KeyCode.E) && interact == true) {
transform.position = destination.position;
}
}
//raycasting for interacts and jumping
void Raycasting ()
{
Debug.DrawLine (lineStart.position, lineEnd.position, Color.green);
Debug.DrawLine (this.transform.position, groundedEnd.position, Color.green);
grounded = Physics2D.Linecast (this.transform.position, groundedEnd.position, 1 << LayerMask.NameToLayer ("Ground"));
if (Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Princess"))) {
interaction = Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Princess"));
interact = true;
} else {
interact = false;
}
}
}