I tried several ways, but I always end up with one error. I wan the GUI buttons to do the same thing as the Keys I have set for movement and attack. I have KeyCode.F for attack I want a GUI.Button to do the same thing. I tried to make a GUI.RepeatButton for my KeyCode.A and D for left and right, but that doesn’t work either. Here’s what I have:
using UnityEngine;
using System.Collections;
using SpriteFactory;
public class player : MonoBehaviour {
public float speed = 1.0f;
private Transform thisTransform;
private Sprite sprite;
private bool flipped;
// Use this for initialization
void Awake () {
thisTransform = transform;
sprite = (Sprite)GetComponent(typeof(Sprite));
}
// Update is called once per frame
void Update () {
Vector3 moveVector = new Vector3(0,0,0);
bool moving = false;
if(Input.GetKey(KeyCode.A)){
moveVector.x -= 1.0f;
moving = true;
}
if(Input.GetKey(KeyCode.D)){
moveVector.x += 1.0f;
moving = true;
}
if(Input.GetKey(KeyCode.F)){
Attack();
} else {
if(!IsAttacking()) {
if(moving) {
Move(moveVector);
} else
Stand();
}
}
}
private void Stand() {
sprite.Stop();
}
private void Move(Vector3 moveVector) {
FlipSprite(moveVector.x);
moveVector *= speed * Time.deltaTime;
thisTransform.position = thisTransform.position + moveVector;
sprite.Play("walk");
}
private void FlipSprite(float x) {
if(x == 0.0f) return;
float xDir = Mathf.Sign(x);
if(!flipped && xDir < 0.0f) {
flipped = true;
sprite.SetFlippedState(true, false);
} else if(flipped&& xDir > 0.0f) {
flipped = false;
sprite.SetFlippedState(false, false);
}
}
private void Attack() {
if(IsAttacking()) return;
sprite.Play("Sword");
}
private bool IsAttacking() {
if(sprite.IsAnimationPlaying("Sword")) return false;
return false;
}
void OnGUI () {
Vector3 moveVector = new Vector3(0,0,0);
bool moving = false;
// Make the first button. If it is pressed, Application.Loadlevel (1) will be executed
if(GUI.RepeatButton(new Rect(1000,300,80,40), "Sword")) {
Attack ();
} else {
if(!IsAttacking()) {
if(moving) {
Move(moveVector);
} else
Stand();
}
// Make the second button.
if(GUI.RepeatButton(new Rect(20,500,80,40), "Left")) {
moveVector.x -= 1.0f;
moving = true;
}
if(GUI.RepeatButton(new Rect(1000,500,80,40), "Right")) {
moveVector.x += 1.0f;
moving = true;
}
}
}
}
All it does is places buttons and screws up my waling animation and attacking animation. It only plays first frame of walk animation when I use the a or d key to walk. The buttons don’t do anything. Please help me!