I got the enemy to move randomly (the code is below) but I have no idea how to make it so it can’t go through walls but yet at the same time be able to go through the floors. Where do I add that and what do I add? I am using Unity 2d
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour
{
private float latestDirectionChangeTime;
private readonly float directionChangeTime = 3f;
private float characterVelocity = 2f;
private Vector2 movementDirection;
private Vector2 movementPerSecond;
void Start()
{
latestDirectionChangeTime = 0f;
calcuateNewMovementVector();
}
void calcuateNewMovementVector()
{
//create a random direction vector with the magnitude of 1, later multiply it with the velocity of the enemy
movementDirection = new Vector2(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f)).normalized;
movementPerSecond = movementDirection * characterVelocity;
}
void Update()
{
//if the changeTime was reached, calculate a new movement vector
if (Time.time - latestDirectionChangeTime > directionChangeTime)
{
latestDirectionChangeTime = Time.time;
calcuateNewMovementVector();
}
//move enemy:
transform.position = new Vector2(transform.position.x + (movementPerSecond.x * Time.deltaTime),
transform.position.y + (movementPerSecond.y * Time.deltaTime));
}
}
So let me start with… im new to unity and all that but ive been watching and learning something everyday. I havent ran into this problem as I havent setup my enemies yet however, did you create a navmesh for the creature to stay on to ensure he doesnt go through walls? idk if that would work with the floor fading portion of it though there may be a way to tweak it for just that. or maybe creating colliders for the walls so he doesnt go through them. Just a thought from a noob
Thanks for the reply! I do have colliders and it still goes through it, its almost like that script ignores the colliders. I don’t have a navmesh yet though, do you know how I create one?
GameObjects won’t respect the physics engine, unless you use the physics engine to move them.
So, if you want to change the transform directly, you’d need to determine your own collisions/trigger zones, and cannot depend on Unity to do it for you without extra work.
If you were to move with the the rigidbody’s velocity, or ‘AddForce’, they would work (assuming they were setup correctly). There is also RigidBody.MovePosition.
*Replace Rigidbody with Rigidbody2D if you’re using 2D.
You could look up how to move with either or how to detect without them. I’m sure there are many posts about the topic.
I don’t think that’s what you want. As I said, you either need to detect these triggers/collisions yourself, or move using the physics system to get them working.