2014-11-07 2 views
1

Привет и спасибо за чтение этого сообщения.Получить плеер, чтобы прыгать с сенсорным экраном управления

У меня есть 2 объекта: Объект игрока и объект JumpButton.

Объект игрока является игроком. ОФК. Объект JumpButton - это объект, который я хочу заставить игрока прыгать, когда вы используете устройство с сенсорным экраном, а также Android-телефон.

Это мой сценарий, который освещается моим JumpButton: используя UnityEngine; используя System.Collections;

using UnityEngine; 
using System.Collections; 

public class JumpButtonScript : MonoBehaviour { 
public GameObject player; 
public GameObject JumpButton; 

// Use this for initialization 
void Start() { 
    player = GameObject.Find ("player"); 
} 

// Update is called once per frame 
void Update() { 
    if ((Input.touchCount == 1) && (Input.GetTouch(0).phase == TouchPhase.Began)) 
    { 

    } 
    } 
} 

Это сценарий, который позволяет мне управлять игроком с помощью клавиш со стрелками.

using UnityEngine; 
using System.Collections; 

public class RobotController : MonoBehaviour { 
//This will be our maximum speed as we will always be multiplying by 1 
public float maxSpeed = 2f; 
public GameObject player; 
public GameObject sprite; 
//a boolean value to represent whether we are facing left or not 
bool facingLeft = true; 
//a value to represent our Animator 
Animator anim; 
//to check ground and to have a jumpforce we can change in the editor 
bool grounded = true; 
public Transform groundCheck; 
public float groundRadius = 1f; 
public LayerMask whatIsGround; 
public float jumpForce = 300f; 
private bool isOnGround = false; 
void OnCollisionEnter2D(Collision2D collision) { 
     isOnGround = true; 
    } 

void OnCollisionExit2D(Collision2D collision) { 
    anim.SetBool ("Ground", grounded); 

    anim.SetFloat ("vSpeed", rigidbody2D.velocity.y); 
    isOnGround = false; 
} 

// Use this for initialization 
void Start() { 

    player = GameObject.Find("player"); 

    //set anim to our animator 
    anim = GetComponent <Animator>(); 
} 


void FixedUpdate() { 
    //set our vSpeed 
    //set our grounded bool 

    grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround); 
    //set ground in our Animator to match grounded 
    anim.SetBool ("Ground", grounded); 

    float move = Input.GetAxis ("Horizontal");//Gives us of one if we are moving via the arrow keys 
    //move our Players rigidbody 
    rigidbody2D.velocity = new Vector3 (move * maxSpeed, rigidbody2D.velocity.y); 
    //set our speed 
    anim.SetFloat ("Speed",Mathf.Abs (move)); 
    //if we are moving left but not facing left flip, and vice versa 
    if (move > 0 && !facingLeft) { 

     Flip(); 
    } else if (move < 0 && facingLeft) { 
     Flip(); 
    } 

} 

void Update(){ 
    if ((isOnGround == true && Input.GetKeyDown (KeyCode.UpArrow)) || (isOnGround == true && Input.GetKeyDown (KeyCode.Space))) { 
     anim.SetBool("Ground",false); 
     rigidbody2D.AddForce (new Vector2 (0, jumpForce)); 
    } 

    if (isOnGround == true && Input.GetKeyDown (KeyCode.DownArrow)) 
    { 
     gameObject.transform.localScale = new Vector3(transform.localScale.x, 0.2f, 0.2f); 
    } 
    if (isOnGround == true && Input.GetKeyUp (KeyCode.DownArrow)) 
    { 
     gameObject.transform.localScale = new Vector3(transform.localScale.x, 0.3f, 0.3f); 
    } 
} 



//flip if needed 
void Flip(){ 
    facingLeft = !facingLeft; 
    Vector3 theScale = transform.localScale; 
    theScale.x *= -1; 
    transform.localScale = theScale; 
} 
} 

Как вы можете видеть, то мне удалось сделать игроку двигаться на клавиши со стрелками, но как я могу сделать его прыгать, когда я нажал кнопку перехода (сенсорный экран нажмите), как на телефон Android?

Надеюсь, вы можете мне помочь.

ответ

0

Если ваша проблема заключается в том, чтобы обрабатывать ввод, попробуйте этот код, мы сделаем луч от камеры к mousepos в экране и проверить тег, чтобы увидеть, что мы попали

public class handleInput: MonoBehaviour { 

    void Update() { 
     if (Input.GetMouseButtonDown (0)) { 
      Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
      RaycastHit hit; 
      if (Physics.Raycast(ray, out hit)) { 
       if (hit.collider.tag=="jumpbutton"){ 
        jump(); 
       }  
      } 
     } 
    } 
} 

и для прыжков части вы можете сделать это , добавив силы игроку, чтобы отправить его, и сила тяжести должна была сбить его

if (grounded == true) 
    { 
     rigidbody.AddForce(Vector3.up* jumpSpeed); 

     grounded = false; 
    } 
+0

Спасибо за ваш ответ. Но ничего не происходит, когда я нажимаю кнопку. –

+0

Вы добавили тег jumpbutton в свою кнопку gameobject –

+0

У меня было того, что вы видите в коде выше. Напомним, что im новый для этого, так что тег, как я помещаю это, –

Смежные вопросы