Tuesday, January 26, 2016

Post 4

-Now we need to add a function in Player that will push the player backwards when touched by the monster. Here is the updated Code:

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

Vector3 pos = this.GetComponent<Transform>().position;
if(Input.GetKey(KeyCode.UpArrow))
{
pos.z += 0.1f;
}
if(Input.GetKey(KeyCode.DownArrow))
{
pos.z -= 0.1f;
}
if(Input.GetKey(KeyCode.RightArrow))
{
pos.x += 0.1f;
}
if(Input.GetKey(KeyCode.LeftArrow))
{
pos.x -= 0.1f;
}
this.GetComponent<Transform>().position = pos;
}

public void playerHit(Vector3 hitPoint)
{
Vector3 direction = this.GetComponent<Transform>().position - hitPoint;

this.GetComponent<Rigidbody>().velocity = direction.normalized * 20;
//Debug.Log ("Hit");
}
}


- This function (playerHit) is public, so its visible by anyone and can be used by anyone, it returns void so we don't have to return anything, and receives a Vector3 called hitPoint, this is passed by the enemy and its the enemy position at the time it hits the player
-playerHit basically finds the direction is should move the player by using the hitPoint and the player position
-Then gets the Rigidbody component and applie a velocity to it using the direction we calculated and a rate (we use 20, which is a terrible way to do it but for this example it will suffice)

-Run Unity and we should have an enemy chasing the player, cooling down when it hits the player and the player bouncing away from the enemy.

No comments:

Post a Comment