Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

unity3d - Unity2D C# Detecting walls between enemy and character

I'm trying to make a roguelike styled game (to put you in context). I'm trying to make a script that makes the enemies follows the main character but stops when there is a wall between.

So I'm trying to make this with Raycasting, if the ray detects a wall between the enemie and the character, the enemie won't move.

Well, the results for now are horrible.

The code I have is something like this:

// Start is called before the first frame update
void Start()
{
    followCharacter = false;
}

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

    


    if (followCharacter == true)
    {
        FollowCharacter();
        RayCast();
    }
}



private void OnTriggerStay2D(Collider2D collision)
{
    if(collision.tag == "Character")
    {
        followCharacter = true;
    }
}
private void OnTriggerExit2D(Collider2D collision)
{
    if (collision.tag == "Character")
    {
        followCharacter = false ;
    }
}



private void FollowCharacter()
    {//Just a Vector2.MoveTowards Script

    controlador.transform.position = Vector2.MoveTowards(controlador.transform.position, controladorPersonaje.transform.position, speed * Time.deltaTime);
}


private void RayCast()
{
    hit = Physics2D.Raycast(enemieTransform.position, character.transform.position); //that character 
                                                                                   //is a game 
                                                                                   //object
    Debug.DrawRay(transformPropio.position, character.transform.position *10f, Color.yellow);
    if (hit.collider.gameObject.tag == "Wall")
    {
        followCharacter = false;
    }
}

I think there must be something wrong in the logic im trying to follow. I want the Ray of the Raycast to always follow the character.

I must clarify that the Collider that is cheking the collisions is a circle around the enemie.

Thanks for all!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...