Moving and Sound example
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class keyboardInput : MonoBehaviour {
private Rigidbody2D rigidbody2D;
public float JumpForce;
public int highScore;
private AudioSource jumpSound;
public float movespeed;
// Use this for initialization
void Start () {
rigidbody2D = gameObject.GetComponent<Rigidbody2D>();
// prepare sounds
GameObject se = GameObject.FindGameObjectWithTag("SoundEngine");
AudioSource[] allSounds = se.GetComponents<AudioSource>();
jumpSound = allSounds[0];
}
// Update is called once per frame
void Update () {
if (Input.GetKey(KeyCode.LeftArrow))
{
gameObject.transform.position = gameObject.transform.position + Vector3.left * movespeed;
}
if (Input.GetKey(KeyCode.RightArrow))
{
gameObject.transform.position = gameObject.transform.position + Vector3.right * movespeed;
}
if (Input.GetKeyDown(KeyCode.Space))
{
//jump
Debug.Log("Space key pressed...");
rigidbody2D.AddForce(transform.up * JumpForce * 100);
//play sound
jumpSound.Play();
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag.Equals("Star"))
{
Debug.Log("star collision");
Destroy(other.gameObject);
highScore = highScore + 1;
GameObject.FindGameObjectWithTag("Score").
GetComponent<Text>().text = "Score: " + highScore;
}
}
}