Question by
nesterio · Jun 18, 2019 at 10:01 AM ·
aiphysics2dcollision2d
Simple moving ai which changes direction to opposite when hits the wall,Simple AI that changes it's direction when hits wall
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class VacuumAI : MonoBehaviour {
bool right = true;
public float maxSpeed = 3;
public float speed = 50f;
private Rigidbody2D rb2d;
// Start is called before the first frame update
void Start()
{
Physics2D.IgnoreLayerCollision(9, 9);
rb2d = gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
}
void FixedUpdate(){
if(right == true){
rb2d.AddForce(Vector2.right * speed);
}
if(right == false){
rb2d.AddForce(Vector2.left * speed);
}
if (rb2d.velocity.x > maxSpeed){
rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
}
if (rb2d.velocity.x < -maxSpeed){
rb2d.velocity = new Vector2(-maxSpeed, rb2d.velocity.y);
}
}
void OnCollisionEnter2D(Collision2D coll) {
if (right == true && coll.gameObject.tag == "Wall"){
right = false;
transform.localScale = new Vector3(-1,1,1);
}
if (right == false && coll.gameObject.tag == "Wall"){
right = true;
transform.localScale = new Vector3(1,1,1);
}
}
} ,using System.Collections; using System.Collections.Generic; using UnityEngine;
public class VacuumAI : MonoBehaviour {
bool right = true;
public float maxSpeed = 3;
public float speed = 50f;
private Rigidbody2D rb2d;
// Start is called before the first frame update
void Start()
{
Physics2D.IgnoreLayerCollision(9, 9);
rb2d = gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
}
void FixedUpdate(){
if(right == true){
rb2d.AddForce(Vector2.right * speed);
}
if(right == false){
rb2d.AddForce(Vector2.left * speed);
}
if (rb2d.velocity.x > maxSpeed){
rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
}
if (rb2d.velocity.x < -maxSpeed){
rb2d.velocity = new Vector2(-maxSpeed, rb2d.velocity.y);
}
}
void OnCollisionEnter2D(Collision2D coll) {
if (right == true){
right = false;
transform.localScale = new Vector3(-1,1,1);
}
if (right == false){
right = true;
transform.localScale = new Vector3(1,1,1);
}
}
}
Comment
Your answer
Follow this Question
Related Questions
OnCollisionExit2D no longer gives contact information 0 Answers
Collision not working in APK , but works in Unity Remote? 1 Answer
Is calling OnCollisionEnter2D on allot of GameObjects leading to worse performance? 0 Answers
Is there any way to access physics calculations beforehand? 1 Answer
2d simple ai and spawning 1 Answer