How best to detect when a charcter object cannot move?
Hey
i have an idea for a game which has levels contianing platforms. How best can i detect when the character has moved to the edge of a platform?
ordinarily, if it were rectangular, then i could simply put in the co-ordinate limits, but some of my levels will be oddly shaped.
When i press a key to move the character in a direction i want to check they can move. Currently i am simply checking the colliders for a "Floor" tag, which seems inefficient.
any suggestions?
Answer by Daemonhahn · Jul 25, 2017 at 06:12 PM
Do a raycast downwards a small amount to detect the floor, raycasting only on the floor layer. If its a hit you set a bool to true (call it grounded or something similar) to determine that you are grounded. Otherwise you set it to false if your not grounded. Do this every update.
Then in your movement code, only move if that bool is true.
Here is a tutorial with some code snippets so you can get started quickly :)
Answer by PersianKiller · Jul 24, 2017 at 06:32 AM
Add a gameObject to your character to check that the character is on ground or not,
using UnityEngine; using System.Collections;
public class ZombieMove : MonoBehaviour {
public float zombieMoveSpeed;
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask whatisGround;
public bool ZombieIsGrounded;
// Update is called once per frame
void Update () {
move ();
}
public void move(){
ZombieIsGrounded = Physics2D.OverlapCircle (GroundCheck.position,GroundCheckRadius,whatIsGround);
if (!ZombieIsGrounded) {
zombieMoveSpeed = -zombieMoveSpeed;
}
if (zombieMoveSpeed > 0) {
transform.localScale = new Vector3 (1,1,1);
}
if (zombieMoveSpeed < 0) {
transform.localScale = new Vector3 (-1,1,1);
} GetComponent ().velocity = new Vector2 (zombieMoveSpeed, GetComponent ().velocity.y);
}
then go to unity and place your groundCheck object below you character ,so when your character moves out of a layer that named Ground, it will moveBack, .
Answer by wizbit · Jul 24, 2017 at 07:31 AM
Hey "PersianKiller",
Thanks for the response so quick.
My character moves in a set spacing routine, so i would need to check that i can move to a position before i actually move, so although this is great i do not think it would work unless i cerated a gameobject in front of the character.
could use a "LineCast" script work from the character to the ground (x) spaces in front?
hi,please put a screenShot of your game it might help others to help you.