Raycast issue with chase AI - c#

In my script, I have a patrol method and a chase method. My chase code using ray cast is not working properly. The only thing that works is my AI patrol code. When I hit a ray cast that I assign, it doesn't chase me. However, when I remove the patrol code in my script, my chase code works fine. What would be the problem? I want my AI to Patrol and Chase. If there is any collision and if the player is outside of the collision, the AI will start to patrol again
public class LineTrigger : MonoBehaviour {
private Transform targett;
public Transform sightStart, sightEnd;
public bool spotted = false;
public GameObject arrow;
public GameObject target;
public bool facingRight = false;
public float speed = 8;
[SerializeField]
float moveSpeed = 3f;
Rigidbody2D rb;
Vector3 localScale;
float dirX;
Vector3 directionToTarget;
void Start()
{
localScale = transform.localScale;
rb = GetComponent<Rigidbody2D> ();
dirX = -1f;
target = GameObject.Find ("Girl");
}
void Update()
{
if (transform.position.x < 1f)
dirX = 1f;
else if (transform.position.x > 20f)
dirX = -1f;
Raycasting ();
Behaviours ();
}
void Raycasting ()
{
Debug.DrawLine (sightStart.position, sightEnd.position);
spotted = Physics2D.Linecast (sightStart.position, sightEnd.position, 1 << LayerMask.NameToLayer ("Girl"));
}
void Behaviours()
{
if (spotted == true) {
arrow.SetActive (true);
directionToTarget = (target.transform.position - transform.position).normalized;
rb.velocity = new Vector2 (directionToTarget.x * moveSpeed, directionToTarget.y * moveSpeed);
}
else
{
arrow.SetActive (false);
}
}
void FixedUpdate()
{
rb.velocity = new Vector2 (dirX * moveSpeed, rb.velocity.y);
}
void LateUpdate()
{
CheckWhereToFace ();
}
void CheckWhereToFace()
{
if (dirX > 0)
facingRight = false;
else if (dirX < 0)
facingRight = true;
if (((facingRight) && (localScale.x < 0)) || ((!facingRight) && (localScale.x > 0)))
localScale.x *= -1;
transform.localScale = localScale;
}
}

I think you are missing a if(!spotted) in your FixedUpdate

Related

How to flip 2D sprite when you move mouse cursor from Left to Right

I am attempting to make 2D topdown shooter game. I first implemented weapon rotation and it worked fine. However, after implementing character sprite flip, the weapon sprite now doesn't rotate to right and the character sprite went weird. What am I doing wrong?
Character Movement Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float speed;
private Rigidbody2D rb;
Vector2 movement;
bool facingRight = true;
// Update is called once per frame
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (mousePos.x > transform.position.x && facingRight)
{
flip();
}
else if (mousePos.x > transform.position.x && !facingRight)
{
flip();
}
}
void flip()
{
facingRight = !facingRight;
transform.Rotate(0f, 180f, 0f);
}
private void FixedUpdate()
{
movement.Normalize();
rb.velocity = new Vector2(movement.x * speed * Time.fixedDeltaTime, movement.y * speed * Time.fixedDeltaTime);
}
}
Weapon Rotation Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunRotation : MonoBehaviour
{
// Gun Rotation Function
public float offset;
private SpriteRenderer spriteRender;
// Start is called before the first frame update
void Start()
{
spriteRender = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
// Gun Rotation Function
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
if (rotZ < 89 && rotZ > -89)
{
Debug.Log("Facing right");
spriteRender.flipY = false;
}
else
{
Debug.Log("Facing left");
spriteRender.flipY = true;
}
}
}
You need just to reverse > in else if condition and it'll work fine
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (mousePos.x > transform.position.x && !facingRight)
{
flip();
}
else if (mousePos.x < transform.position.x && facingRight)
{
flip();
}

I'm getting a spin error, Can you help me fix this it?

I am working on a 2d zombie killing game but there was an error rotating the gun in my code, when I rotate the gun it turns wrong. Can you help me?
Video:https://youtu.be/8kUgXkEZc2M
Here is the code:
[SerializeField] Transform _arm;
float _offset = -90;
Vector3 _startingSize;
Vector3 _armStartingSize;
public GameObject Bullet;
public float BulletSpeed;
public Transform ShootPoint;
#region Start
// Start is called before the first frame update
void Start()
{
_startingSize = transform.localScale;
_armStartingSize = _arm.localScale;
}
#endregion
// Update is called once per frame
void Update()
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 perendicular = _arm.position - mousePos;
Quaternion val = Quaternion.LookRotation(Vector3.forward, perendicular);
val *= Quaternion.Euler(0, 0, _offset);
_arm.rotation = val;
if(transform.position.x - mousePos.x < -0.1)
{
transform.localScale = _startingSize;
_arm.localScale = _armStartingSize;
}
else if(transform.position.x - mousePos.x > 0.1)
{
transform.localScale = new Vector3(-_startingSize.x, _startingSize.y, _startingSize.z);
_arm.localScale = new Vector3(-_armStartingSize.x, -_armStartingSize.y, _armStartingSize.z);
}
if (Input.GetMouseButtonDown(0))
{
shoot();
}
}
void shoot()
{
cineShake.Instance.ShakeCamera(5f, .1f);
GameObject BulletIns = Instantiate(Bullet, ShootPoint.position, ShootPoint.rotation);
BulletIns.GetComponent<Rigidbody2D>().AddForce(BulletIns.transform.right * BulletSpeed);
}

Multiple Error Messages C# Script Unity. Need some help (beginning scripter)

I work in unity since 2 days now. I was scripting for a 2d Sprite. When i added the last elements the script didn't work anymore. but i want to make this work. can someone look at the error messages and then to the script to see what is wrong with it.
Error 1: (25,38): error CS1503: Argument #2' cannot convertfloat' expression to type `UnityEngine.Vector2'
Error 2: (25,38): error CS1502: The best overloaded method match for `UnityEngine.Physics2D.OverlapBox(UnityEngine.Vector2, UnityEngine.Vector2, float)' has some invalid arguments
Script:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float speed = 5f;
public float jumpSpeed = 8f;
private float movement = 0f;
private Rigidbody2D rigidBody;
public Transform groundCheckPoint;
public float groundCheckRadius;
public LayerMask groundLayer;
private bool isTouchingGround;
void Start()
{
rigidBody = GetComponent<Rigidbody2D> ();
}
void Update()
{
isTouchingGround = Physics2D.OverlapBox (groundCheckPoint.position, groundCheckRadius, groundLayer);
movement = Input.GetAxis ("Horizontal");
if (movement > 0f)
{
rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
}
else if (movement < 0f)
{
rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
}
else
{
rigidBody.velocity = new Vector2(0, rigidBody.velocity.y);
}
if (Input.GetButtonDown("Jump") && isTouchingGround)
{
rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
}
}
}
isTouchingGround = Physics2D.OverlapCircle(groundCheckPoint.position, groundCheckRadius, groundLayer);
If you still wanting to use the OverlapBox, here's the link to the Scripting API for it (I personally got here whenever I'm stuck): Unity - Scripting API: Physics2D.OverlapBox
Also, I would move the coding for player jumping to the FixedUpdate function instead of the Update function. Seen below is my code from my player controller script from a 2D platformer that I did for a game jam. Hope this helps.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed;
public float jumpForce;
private float moveInput;
private Rigidbody2D rb;
private bool facingRight = true;
private bool isGrounded;
public Transform groundCheck;
public float checkedRadius;
public LayerMask whatIsGround;
private int extraJumps;
private void Start()
{
extraJumps = 1;
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkedRadius, whatIsGround);
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
if (facingRight == false && moveInput > 0)
{
Flip();
}
else if (facingRight == true && moveInput < 0)
{
Flip();
}
}
private void Update()
{
if (isGrounded == true)
{
extraJumps = 2;
}
if (Input.GetKeyDown(KeyCode.W) && extraJumps > 0)
{
rb.velocity = Vector2.up * jumpForce;
extraJumps--;
}
else if (Input.GetKeyDown(KeyCode.W) && extraJumps == 0 && isGrounded == true)
{
rb.velocity = Vector2.up * jumpForce;
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
}

How do i make enemy AI face the player

I'm trying to find a way to rotate the enemy towards the player. Currently it follows/stops and shoots the player. Have not figured out how to make it rotate. Please help if you can. I've tried couple of different things on here but they dont seem to work.
I've tried creating a Flip function with isFacingRight.
private bool facingRight;
public float speed;
public float stoppingDistance;
public float retreatDistance;
private Animator enemyAnimation;
private bool isDead;
private float direction;
public static bool enemyShoot = false;
private float timeBtwShots;
public float startTimeBtwShots;
public GameObject projectile;
private Transform player;
[SerializeField]
private Stat health;
private void Awake()
{
health.Initialize();
}
// Start is called before the first frame update
void Start()
{
//Player tag
player = GameObject.FindGameObjectWithTag("Player").transform;
enemyAnimation = GetComponent<Animator>();
isDead = false;
}
// Update is called once per frame
void Update()
{
if (Vector2.Distance(transform.position, player.position) > stoppingDistance)
{
transform.position = Vector2.MoveTowards(transform.position, player.position, speed * Time.deltaTime);
timeBtwShots = startTimeBtwShots;
if(player.position.x > transform.position.x && !facingRight) //if the target is to the right of enemy and the enemy is not facing right
Flip();
if(player.position.x < transform.position.x && facingRight)
Flip();
}
else if (Vector2.Distance(transform.position,player.position) <= stoppingDistance && Vector2.Distance(transform.position,player.position)>retreatDistance)
{
transform.position = this.transform.position;
}
else if (Vector2.Distance(transform.position, player.position) > retreatDistance)
{
transform.localScale = new Vector2(-1f, 1f);
transform.position = Vector2.MoveTowards(transform.position, player.position, -speed * Time.deltaTime);
timeBtwShots = 100;
enemyAnimation.SetTrigger("Attack");
}
if (enemyShoot == true)
{
//Stops animation Loop
enemyShoot = false;
enemyAnimation.SetTrigger("Shoot");
}
if (timeBtwShots <= 0)
{
Instantiate(projectile, transform.position, Quaternion.identity);
timeBtwShots = startTimeBtwShots;
}
else
{
timeBtwShots -= Time.deltaTime;
}
if (health.CurrentVal == 0)
{
timeBtwShots = 100;
FindObjectOfType<SoundsScript>().Play("SaibaDeath");
isDead = true;
enemyAnimation.SetBool("Dead", isDead);
Destroy(gameObject, 2f);
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "ProjectileEnem")
{
health.CurrentVal -= 50;
enemyAnimation.SetTrigger("Hurt");
}
}
//Disables enemeies when off screen
private void OnBecameInvisible()
{
GetComponent <Enemy> ().enabled = false;
}
//Re enables enemies once they are visible
private void OnBecameVisible()
{
GetComponent<Enemy>().enabled = true;
}
void Flip(){
Vector3 scale = transform.localScale;
scale.x *= -1;
transform.localScale = scale;
facingRight = !facingRight;
}
}
Try this:
spriteRenderer.flipX = transform.position.x < player.position.x;
SpriteRenderer contains the flipX and flipY property, you do not need to create your own Flip() function.
You need a reference to the SpriteRenderer on your GameObject.
The above code is assuming that your sprite faces left on default. If your sprite faces right normally, change the < to >.

Smooth fall in Unity - C#

I am working on a Character Controller Script and everything is working fine but the problem is that once my player starts to fall it is so sudden and jerks down. I would like the player to gradually fall down, this is my character controller script -
using UnityEngine;
using System.Collections;
public class CharacterController : MonoBehaviour {
public float inputDelay = 0.1f;
public float forwardVel = 12;
public float rotateCel = 12;
public float JumpHeight = 20;
public Vector3 Gravity = new Vector3 (0, -180, 0);
public bool CanPress;
private float jumpTime;
public float _initialJumpTime = 0.4f;
//[HideInInspector]
public bool isGrounded;
Quaternion targetRotation;
Rigidbody rBody;
Vector3 forwardInput, turnInput;
public bool HasJumped;
public Quaternion TargetRotation
{
get {return targetRotation;}
}
// Use this for initialization
void Start () {
Physics.gravity = Gravity;
targetRotation = transform.rotation;
if (GetComponent<Rigidbody> ())
rBody = GetComponent<Rigidbody> ();
else {
Debug.LogError("Character Needs Rigidbody");
}
// forwardInput = turnInput = 0;
forwardInput = turnInput = Vector3.zero;
}
// Update is called once per frame
void Update () {
GetInput ();
//Turn ();
if (CanPress == true) {
if (Input.GetKeyDown (KeyCode.Space)) {
HasJumped = true;
jumpTime = _initialJumpTime;
}
}
if (HasJumped == true) {
rBody.useGravity = false;
jumpTime -= 1 * Time.deltaTime;
if (jumpTime > 0) {
Jump();
}
else {
HasJumped = false;
rBody.useGravity = true;
}
}
}
void GetInput() {
//forwardInput = Input.GetAxis ("Vertical");
//turnInput = Input.GetAxis ("Horizontal");
forwardInput = new Vector3 (Input.GetAxis ("Horizontal") * rotateCel, 0, Input.GetAxis ("Vertical") * forwardVel);
forwardInput = transform.TransformDirection (forwardInput);
if (Input.GetKeyUp (KeyCode.Space)) {
//HasJumped = false;
}
}
void Jump() {
Vector3 up = transform.TransformDirection (Vector3.up);
GetComponent<Rigidbody> ().AddForce (up * 5, ForceMode.Impulse);
}
void FixedUpdate() {
Run ();
}
void Run() {
if (Mathf.Abs (10) > inputDelay) {
//Move
//rBody.velocity = transform.forward * forwardInput * forwardVel;
rBody.velocity = forwardInput;
} else {
//zero velocity
rBody.velocity = Vector3.zero;
}
}
void Turn() {
// targetRotation *= Quaternion.AngleAxis (rotateCel * turnInput * Time.deltaTime, Vector3.up);
// transform.rotation = targetRotation;
}
void OnTriggerEnter(Collider col) {
isGrounded = true;
CanPress = true;
}
void OnTriggerExit(Collider col) {
isGrounded = false;
CanPress = false;
}
}
My character has a Rigidbody attactches which uses gravity and has X,Y,Z constraints for Rotation.
The player goes up smoothly and falls down smoothly but the transition between the two is very abrupt and sudden.
Thanks for the help. :)
Okay, so I took your code and had a play.
I think the issue was that in your Run() function, you were altering the velocity of the rigidbody which was affecting your jumping.
I've taken that stuff out and improved your script slightly and tested it. Attach this to a capsule with a rigidbody on it, with a floor underneath with a box collider on and hit space, and you should get a smooth jump.
Your new(ish) script:
using UnityEngine;
using System.Collections;
public class CharacterController : MonoBehaviour
{
public float inputDelay = 0.1f;
public float forwardVel = 12;
public float rotateCel = 12;
public float jumpHeight = 10;
private float jumpTime;
public float _initialJumpTime = 0.4f;
//[HideInInspector]
public bool isGrounded;
Quaternion targetRotation;
Rigidbody rBody;
Vector3 forwardInput, turnInput;
public bool canJump;
public Quaternion TargetRotation
{
get { return targetRotation; }
}
void Start()
{
targetRotation = transform.rotation;
if (GetComponent<Rigidbody>())
rBody = GetComponent<Rigidbody>();
else
{
Debug.LogError("Character Needs Rigidbody");
}
// forwardInput = turnInput = 0;
forwardInput = turnInput = Vector3.zero;
}
void Update()
{
GetInput();
//Turn ();
if (Input.GetKeyDown(KeyCode.Space) && canJump)
{
rBody.AddForce(Vector3.up * jumpHeight, ForceMode.Impulse);
}
}
void GetInput()
{
//forwardInput = Input.GetAxis ("Vertical");
//turnInput = Input.GetAxis ("Horizontal");
forwardInput = new Vector3(Input.GetAxis("Horizontal") * rotateCel, 0, Input.GetAxis("Vertical") * forwardVel);
forwardInput = transform.TransformDirection(forwardInput);
}
void FixedUpdate()
{
//Run();
}
void Run()
{
//HERE YOU SET THE RIGIDBODYS VELOCITY, WHICH IS CAUSING YOUR JUMP TO NOT WORK PROPERLY. DO NOT MODIFY THE VELOCITY
//OF A RIGIDBODY
if (Mathf.Abs(10) > inputDelay)
{
//Move
//rBody.velocity = transform.forward * forwardInput * forwardVel;
rBody.velocity = forwardInput;
}
else
{
//zero velocity
rBody.velocity = Vector3.zero;
}
}
void Turn()
{
// targetRotation *= Quaternion.AngleAxis (rotateCel * turnInput * Time.deltaTime, Vector3.up);
// transform.rotation = targetRotation;
}
void OnCollisionEnter(Collision col)
{
isGrounded = true;
canJump = true;
}
void OnCollisionExit(Collision col)
{
isGrounded = false;
canJump = false;
}
}
Couple of points:
name your variables inThisKindOfFashion (jumpHeight, isOnGround, camelCaseExample), having variables beginning with a capital letter like Gravity and JumpHeight can get confusing.
as someone once answered on one of my questions, don't modify the velocity of a rigidbody unless you know what you are doing! Seems odd, but after following that advice I've never had a problem since!
In your script I have used OnCollision rather than OnTrigger. If you put a floor with a box collider underneath your capsule with a collider, rigidbody and this script on, your character will stop on the ground. If you use a trigger, he will fall through (at least in my experience!)
Happy coding! :-)
Edit
To respond to your comments:
"How do you suggest I move the player"
Movement can be done in a variety of different ways, but I usually use this one all the time unless I need to do something a bit differently:
void Update()
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
transform.position += Vector3.left * speed * Time.deltaTime; //speed could be 5f, for example (f means float);
}
// then do the same for other directions, RightArrow -.right, UpArrow - .forward, DownArrow - .back
}
"How do I adjust how fast the player jumps"
You can alter the jumpHeight variable for a higher or smaller jump. If by faster you mean falls down faster, go to Edit>Project Settings>Physics> and change Y gravity to something smaller, such as -20.
Tutorials can be found here
They have a wide variety of tutorials, and even have ones that come with example projects so you can just put it together following the video.

Categories

Resources