Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by ParyPro · Jan 12, 2019 at 07:05 PM · aienemylevel

Guard AI acting quite weird - Please Help!

Hello! I am still very new to this whole Unity thing but I'm absolutely loving it. I have encountered a big problem in my first 2d game with my Guard AI. The game design is very simple; guide the little square (player) across the platforms in the level to reach the end, with many different Guard AI spread across it shooting out a red ray that, if hit with the player, causes game over.

My main Guard AI is quite simple as well - move back and forth across a single platform, when getting to the end of the platform turning around and shooting out a red beam that covers the length of the platform, causing the player to have to jump up when it shoots to avoid getting hit, with the red beam then disappearing and it moving back across to the other side of the platform.

For some odd reason upon touching down to the platform anywhere to the left of the Guard, even when the beam is not out, the beam automatically and instantly shoots out and kills the player. I have been working at this problem for weeks but my simple lack of coding skills has not allowed me to locate the cause of this. I have attached the entire Guard script here:`using System.Collections; using System.Collections.Generic; using UnityEngine;

[CSHARP]

public class Guard2 : MonoBehaviour {

 public Transform pathHolder;
 Transform player;
 Color originalSpotLightColour;

 public float distance;

 public LineRenderer lineOfSight;
 public Gradient redColor;
 public Gradient greenColor;

 public float speed = 5;
 public float waitTime = .3f;
 public float turnSpeed = 90;

 public Light spotLight;
 public float viewDistance;
 public LayerMask viewMask;
 float viewAngle;

 void Start()
 {
     player = GameObject.FindGameObjectWithTag("Player").transform;
     viewAngle = spotLight.spotAngle;
     originalSpotLightColour = spotLight.color;

     Vector3[] waypoints = new Vector3[pathHolder.childCount];
     for (int i = 0; i < waypoints.Length; i++)
     {
         waypoints[i] = pathHolder.GetChild(i).position;
         waypoints[i] = new Vector3(waypoints[i].x, transform.position.y, waypoints[i].z);
     }

     StartCoroutine(FollowPath(waypoints));
 }

 void Update()
 {
     if (CanSeePlayer())
     {
         spotLight.color = Color.red;
     }
     else
     {
         spotLight.color = originalSpotLightColour;
     }

     RaycastHit2D hitInfo = Physics2D.Raycast(transform.position, transform.right, distance);
     if (hitInfo.collider != null)
     {
         Debug.DrawLine(transform.position, hitInfo.point, Color.red);
         lineOfSight.SetPosition(1, hitInfo.point);
         lineOfSight.colorGradient = redColor;

         if (hitInfo.collider.CompareTag("Player"))
         {
             Destroy(hitInfo.collider.gameObject);
         }

     }
     else
     {
         Debug.DrawLine(transform.position, transform.position + transform.right * distance, Color.green);
         lineOfSight.SetPosition(1, transform.position + transform.right * distance);
         lineOfSight.colorGradient = greenColor;
     }

     lineOfSight.SetPosition(0, transform.position);
 }


 bool CanSeePlayer()
 {
     if (Vector3.Distance(transform.position, player.position) < viewDistance)
     {
         Vector3 dirToPlayer = (player.position - transform.position).normalized;
         float angleBetweenGuardAndPlayer = Vector3.Angle(transform.forward, dirToPlayer);
         if (angleBetweenGuardAndPlayer < viewAngle / 2f)
         {
             if (!Physics.Linecast(transform.position, player.position, viewMask))
             {
                 return true;
             }
         }
     }
     return false;
 }

 IEnumerator FollowPath(Vector3[] waypoints)
 {
     transform.position = waypoints[0];

     int targetWaypointIndex = 1;
     Vector3 targetWayPoint = waypoints[targetWaypointIndex];
     transform.LookAt(targetWayPoint);

     while (true)
     {
         transform.position = Vector3.MoveTowards(transform.position, targetWayPoint, speed * Time.deltaTime);
         if (transform.position == targetWayPoint)
         {
             targetWaypointIndex = (targetWaypointIndex + 1) % waypoints.Length;
             targetWayPoint = waypoints[targetWaypointIndex];
             yield return new WaitForSeconds(waitTime);
             yield return StartCoroutine(TurnToFace(targetWayPoint));
         }
         yield return null;
     }
 }

 IEnumerator TurnToFace(Vector3 lookTarget)
 {
     Vector3 dirToLookTarget = (lookTarget - transform.position).normalized;
     float targetAngle = 90 - Mathf.Atan2(dirToLookTarget.z, dirToLookTarget.x) * Mathf.Rad2Deg;

     while (Mathf.Abs(Mathf.DeltaAngle(transform.eulerAngles.y, targetAngle)) > 0.05f)
     {
         float angle = Mathf.MoveTowardsAngle(transform.eulerAngles.y, targetAngle, turnSpeed * Time.deltaTime);
         transform.eulerAngles = Vector3.up * angle;
         yield return null;
     }
 }

 void OnDrawGizmos()
 {
     Vector3 startPosition = pathHolder.GetChild(0).position;
     Vector3 previousPosition = startPosition;

     foreach (Transform waypoint in pathHolder)
     {
         Gizmos.DrawSphere(waypoint.position, .3f);
         Gizmos.DrawLine(previousPosition, waypoint.position);
         previousPosition = waypoint.position;
     }
     Gizmos.DrawLine(previousPosition, startPosition);

     Gizmos.color = Color.red;
     Gizmos.DrawRay(transform.position, transform.forward * viewDistance);
 }

}

[/CSHARP]

I have many video visuals of this problem that are too large to attach here - if anyone would like to communicate via email to get a visual I would love to send them over! Thanks for taking the time to read and if anyone has any tips/ suggestions to solve this problem please let me know either here or email me at rsrickard@yahoo.com

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image aardappel156 · Jan 12, 2019 at 10:39 PM 0
Share

you can maybe put the video on youtube.

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by DCordoba · Jan 13, 2019 at 12:29 PM

hummm, maybe you have a confusion with your own model, ur model seem to have looking to their right, ie, the render of the model have the face to right (the red axis on world space) and the function CanSeePlayer check the blue axis, its just is a hypotesis of course...

I will try to explain why I think that.

on line 42 u are raycasting a control line, to the right of the transform, I think you want to face the target, with the right, and see if it collide, the red axis (transform.right) is the forward of ur model

 RaycastHit2D hitInfo = Physics2D.Raycast(transform.position, transform.right, distance);

on line 62, u are drawing a control line, I believe you want to figue out where the model are looking again it points to the right

 RaycastHit2D hitInfo = Physics2D.Raycast(transform.position, transform.right, distance);

but, when u check where is the player on CanSeePlayer it calculate the angle between transform.forward and the player so, if the blue axis of ur model is pointing the player or not

at line 76, 77

          float angleBetweenGuardAndPlayer = Vector3.Angle(transform.forward, dirToPlayer);
          if (angleBetweenGuardAndPlayer < viewAngle / 2f)

if ur model is facing its right (its red axis), the blue axis (its forward) is at ur left, and your code detect and try to kill, any at the viewAngle, but centered on the left...

I still don't understand how, if you scan the transform.forward, can draw a Raycast to the transform.right and still collide and destroy the target

btw, I admire how good are u with math, but, there are some helpful functions like Vector2.Lerp() or Quaternion.Lerp() with acceptable (and simple btw) interpolation betwen two points, and, besides use a lot coroutines can use a state machine, with a single coroutine calling separate funcions for each task (avance, rotate, attack), sorry to all the confuse explanation... or intent of, hope this help...

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

171 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Guard AI acting bonkers - Please Help! 0 Answers

How do I make it so that a walking animation plays for the enemy AT THE SAME TIME it is moving toward the player? 0 Answers

How do I go about making a 2d platform enemy ai 1 Answer

Enemy following Player on uneven surface 1 Answer

How to keep count of enemies left 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges