The sprite doesnt seems to be jumping - c#

i am following a brackeys tutorial, the sprite is moving left right but not jumping. "Jump" is working fine but the results are not present in the gameview.it references a script provided by brackeys but i dont whether thats the problem.
Here is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class player_movemnt : MonoBehaviour
{
public CharacterController2D controller;
float horizontal_movement =0f;
public float run_speed = 60f;
bool jump = false;
void Update()
{
horizontal_movement = Input.GetAxisRaw("Horizontal")*run_speed;
if(Input.GetButtonDown("Jump"))
{
jump = true;
Debug.Log("l");
}
}
void FixedUpdate()
{
//move character
controller.Move(horizontal_movement*Time.fixedDeltaTime,false, jump);
jump= false;
}
}
here is the CharacterControl2D scrip
using UnityEngine;
using UnityEngine.Events;
public class CharacterController2D : MonoBehaviour
{
[SerializeField] private float m_JumpForce = 400f; // Amount of force added when the player jumps.
[Range(0, 1)] [SerializeField] private float m_CrouchSpeed = .36f; // Amount of maxSpeed applied to crouching movement. 1 = 100%
[Range(0, .3f)] [SerializeField] private float m_MovementSmoothing = .05f; // How much to smooth out the movement
[SerializeField] private bool m_AirControl = false; // Whether or not a player can steer while jumping;
[SerializeField] private LayerMask m_WhatIsGround; // A mask determining what is ground to the character
[SerializeField] private Transform m_GroundCheck; // A position marking where to check if the player is grounded.
[SerializeField] private Transform m_CeilingCheck; // A position marking where to check for ceilings
[SerializeField] private Collider2D m_CrouchDisableCollider; // A collider that will be disabled when crouching
const float k_GroundedRadius = .2f; // Radius of the overlap circle to determine if grounded
private bool m_Grounded; // Whether or not the player is grounded.
const float k_CeilingRadius = .2f; // Radius of the overlap circle to determine if the player can stand up
private Rigidbody2D m_Rigidbody2D;
private bool m_FacingRight = true; // For determining which way the player is currently facing.
private Vector3 m_Velocity = Vector3.zero;
[Header("Events")]
[Space]
public UnityEvent OnLandEvent;
[System.Serializable]
public class BoolEvent : UnityEvent<bool> { }
public BoolEvent OnCrouchEvent;
private bool m_wasCrouching = false;
private void Awake()
{
m_Rigidbody2D = GetComponent<Rigidbody2D>();
if (OnLandEvent == null)
OnLandEvent = new UnityEvent();
if (OnCrouchEvent == null)
OnCrouchEvent = new BoolEvent();
}
private void FixedUpdate()
{
bool wasGrounded = m_Grounded;
m_Grounded = false;
// The player is grounded if a circlecast to the groundcheck position hits anything designated as ground
// This can be done using layers instead but Sample Assets will not overwrite your project settings.
Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
{
m_Grounded = true;
if (!wasGrounded)
OnLandEvent.Invoke();
}
}
}
public void Move(float move, bool crouch, bool jump)
{
// If crouching, check to see if the character can stand up
if (!crouch)
{
// If the character has a ceiling preventing them from standing up, keep them crouching
if (Physics2D.OverlapCircle(m_CeilingCheck.position, k_CeilingRadius, m_WhatIsGround))
{
crouch = true;
}
}
//only control the player if grounded or airControl is turned on
if (m_Grounded || m_AirControl)
{
// If crouching
if (crouch)
{
if (!m_wasCrouching)
{
m_wasCrouching = true;
OnCrouchEvent.Invoke(true);
}
// Reduce the speed by the crouchSpeed multiplier
move *= m_CrouchSpeed;
// Disable one of the colliders when crouching
if (m_CrouchDisableCollider != null)
m_CrouchDisableCollider.enabled = false;
} else
{
// Enable the collider when not crouching
if (m_CrouchDisableCollider != null)
m_CrouchDisableCollider.enabled = true;
if (m_wasCrouching)
{
m_wasCrouching = false;
OnCrouchEvent.Invoke(false);
}
}
// Move the character by finding the target velocity
Vector3 targetVelocity = new Vector2(move * 10f, m_Rigidbody2D.velocity.y);
// And then smoothing it out and applying it to the character
m_Rigidbody2D.velocity = Vector3.SmoothDamp(m_Rigidbody2D.velocity, targetVelocity, ref m_Velocity, m_MovementSmoothing);
// If the input is moving the player right and the player is facing left...
if (move > 0 && !m_FacingRight)
{
// ... flip the player.
Flip();
}
// Otherwise if the input is moving the player left and the player is facing right...
else if (move < 0 && m_FacingRight)
{
// ... flip the player.
Flip();
}
}
// If the player should jump...
if (m_Grounded && jump)
{
// Add a vertical force to the player.
m_Grounded = false;
m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
}
}
private void Flip()
{
// Switch the way the player is labelled as facing.
m_FacingRight = !m_FacingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
i am completely dumbfounded with this problem.

If you're using a separate class to handle your movement, it's always ideal to include it alongside your question. So others wont have to search for it.
Your code appears okay, at least based on the tutorial you've mentioned. Double-check that them_GroundCheck GameObject of CharacterController2D is on the ground rather than on the bottom of the player, as that's responsible for ensuring you can jump in the first place.
public CharacterController2D characterController;
public float runSpeed = 60f;
private float _horizontalMovement;
private bool _jump;
private void Update()
{
_horizontalMovement = Input.GetAxisRaw("Horizontal") * runSpeed;
if (Input.GetButtonDown("Jump"))
{
_jump = true;
}
}
private void FixedUpdate()
{
characterController.Move(_horizontalMovement * Time.fixedDeltaTime, false, _jump);
_jump = false;
}
I'd recommend working backwards and ensuring your CharacterController2D is set up correctly to support the jump, including any attributes you need to add in the inspector window. Such as a reference to GroundCheck and its LayerMask.

Related

How to create a camera that combines both forced movement and smooth player following

Context
So I'm making a clone of Crossy Roads where the camera follows the player. It does some linear interpolation (Lerp) after moving, and the camera starts moving away from the player in the positive direction (x-axis until camera reaches to a certain range where player is not visible enough). Things I have tried is by flagging it, but I think I'm doing it wrong.
Problem
I have done my camera movements accordingly, but I am having an issue where the conditions are not properly met. I'm get the offset camera after not moving, but it does not the Lerp, and vice-versa. I want both to happen after a certain condition after the game starts. When the player moves, the camera follows it in Lerp. However, once the player is "Idle", its still Lerping. I want the camera to continue by itself and at the same time focus at the player's object.
Example
Camera with Lerp, but not moving away from the player
Camera moving away, but not following player with lerp
Code
CameraController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
** Camera following player (Smoothing and angle): https://youtu.be/4HpC--2iowE
** Maximo: https://www.youtube.com/watch?v=bXNFxQpp2qk&ab_channel=iHeartGameDev
** Moving character relative to camera: https://forum.unity.com/threads/moving-character-relative-to-camera.383086/
** Camera follow v2: https://youtu.be/Jpqt2gRHXtc?list=PLq_nO-RwB516fNlRBce0GbtJSfysAjOgU
*/
public class CameraController : MonoBehaviour
{
public GameObject player;
public PlayerControl playerControlScript;
private Vector3 newCameraPos;
public bool stillIdle;
void Start()
{
stillIdle = false;
PlayerControl playerControlScript = GetComponent<PlayerControl>();
}
void LateUpdate()
{
player = GameObject.FindGameObjectWithTag("Player");
if (playerControlScript.GetfirstInput()) //True
{
stillIdle = true;
newCameraPos = Vector3.Lerp(transform.position, playerControlScript.transform.position, Time.deltaTime);
transform.position = new Vector3(newCameraPos.x, 1, newCameraPos.z);
}
if (stillIdle)
transform.position = new Vector3(transform.position.x + 0.69f * Time.deltaTime, transform.position.y, transform.position.z); //Moving camera away effect
}
}
PlayerControl.cs
public class PlayerControl : MonoBehaviour
{
bool firstInput;
Vector3 startPos;
Vector3 endPos;
public bool GetfirstInput() //I was learning how to have a Get function while my member was private from another script file
{
return firstInput;
}
void Update()
{
if (Input.GetButtonDown("up") || Input.GetButtonDown("left") || Input.GetButtonDown("right") || Input.GetButtonDown("down"))
{
//if game starts
{
//Other variables being initialized here
firstInput = true;
}
}
}
}
Hierarchy/Inspector
Main Camera
Player Object
Some help would be appreciate it. I feel I have been staring at this problem and I bet it is something minimal and small from just thinking it.
Let me know if you need clarifications. I'm happy to edit and answer them for everyone
If player in your game does not change, you don't have to find the player reference in each LateUpdate().
I notice that once stillIdle is set true, it never goes back to false, is this your intention to do that?
You call Lerp when playerControlScript.GetfirstInput() is true, so maybe we need to look at its implementation. Maybe it turns true in some conditions you do not intend it to.
Maybe Try this
public class PlayerControl : MonoBehaviour
{
private bool _hasFireFirstInput = false;
private bool _isIdle = true;
public bool IsIdle => _isIdle;
public bool HasFireFirstInput => _hasFireFirstInput;
private void Update()
{
if (Input.GetButton("Horizontal") || Input.GetButton("Vertical"))
{
_hasFireFirstInput = true;
_isIdle = false;
Vector3 pos = transform.position;
pos = new Vector3(pos.x, pos.y, pos.z + .2f * Time.deltaTime);
transform.position = pos;
}
else
{
_isIdle = true;
}
}
}
I use Input.GetButton() rather than Input.GetButtonDown(), since the later only return true at the frame the button is pressed, meaning that if i long-press the button, it will return false after the next frame.
public class CameraController : MonoBehaviour
{
[SerializeField] PlayerControl _playerControlScript;
[SerializeField] Vector3 _offset;
[SerializeField] float _lerpSpeed;
bool _iskeepLerping = false;
float _lerpVal = 0f;
private void LateUpdate()
{
if (!_playerControlScript.HasFireFirstInput)
{
return;
}
if (_playerControlScript.IsIdle)
{
MoveAway();
}
else
{
Lerp();
}
}
private void MoveAway()
{
_iskeepLerping = false;
transform.position = new Vector3(transform.position.x + 0.69f * Time.deltaTime, transform.position.y, transform.position.z);
}
private void Lerp()
{
if (!_iskeepLerping)
{
_lerpVal = 0f;
}
Vector3 newCameraPos = Vector3.Lerp(transform.position, _playerControlScript.transform.position + _offset, _lerpVal);
transform.position = newCameraPos;
_lerpVal += _lerpSpeed * Time.deltaTime;
_iskeepLerping = true;
}
}

How to have a rigidbody object "ride" a falling platform, while still being able to move horizontally

I'm making a 2D game in Unity, which has falling platforms that the player can "ride" down. I want the player to still be able to move left or right (ie horizontally) while standing on a falling platform. Without additional code, just using the Rigidbody physics, the player does fall along with the platform, but the falling is choppy, and the game doesn't always see the player is standing on the platform (important because the player can only jump while standing on something).
I've tried setting the player object's transform.translate, which prevents the player from moving left or right as long as it is touching the platform. I've also tried setting the player object's transform.parent to the platform's transform, but that "glues" the player in place to the platform, preventing even jumping. I've also tried searching for a solution/example, and there are plenty of examples for riding a left-right moving platform, but I haven't been able to get those examples to work for a falling platform.
Here is the script controlling the players left-right movement and jumping. This is attached to the player object:
public class Player : MonoBehaviour
{
public float jumpForce = 5;
public float horizontalSpeed = 0.1F;
public LayerMask whatIsGround;
private Rigidbody2D rb2d;
private Collider2D myCollider;
private bool grounded;
private float lastHorizontalInput;
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
myCollider = GetComponent<Collider2D>();
}
void Update()
{
// If the player is trying to jump, only do so if the player is on a platform
grounded = Physics2D.IsTouchingLayers(myCollider, whatIsGround);
if (Input.GetKeyDown(KeyCode.Space) && grounded)
{
rb2d.velocity = new Vector2(rb2d.velocity.x, jumpForce);
}
MoveHorizonltally();
}
private void MoveHorizonltally()
{
float horizontalVelocity;
float horizontalInput = Input.GetAxis("Horizontal");
horizontalVelocity = GetHorizontalVelocity(horizontalInput);
if (horizontalVelocity != 0)
{
rb2d.position = new Vector2(rb2d.position.x + horizontalVelocity, rb2d.position.y);
}
}
private float GetHorizontalVelocity(float horizontalInput)
{
// Default to no horizontal motion
float result = 0;
bool leftPressed = Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow);
bool rightPressed = Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow);
// Only a left key is being pressed; the player is going left
if (leftPressed && !rightPressed)
{
result = -1 * horizontalSpeed;
}
// Only a right key is being pressed; the player is going right
else if (rightPressed && !leftPressed)
{
result = horizontalSpeed;
}
// Both keys are being pressed
else if (leftPressed && rightPressed)
{
// The most recent key press gets priority; ignore the oldest key press
if (lastHorizontalInput < 0)
{
// Oldest key pressed is a left direction, so go right
result = horizontalSpeed;
}
else
{
// Oldest key pressed is a right direction, so go left
result = -1 * horizontalSpeed;
}
}
lastHorizontalInput = horizontalInput;
return result;
}
}
Here is the script responsible for making the platform fall. This is attached to the platform object:
public class PlatformFalling : MonoBehaviour
{
public float fallSpeed;
private GameObject player;
public void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
}
// Update is called once per frame
void Update()
{
bool playerIsOnPlatform = player.GetComponent<Collider2D>().IsTouching(GetComponent<Collider2D>()); ;
Vector2 fallDistance = Vector2.down * fallSpeed;
transform.Translate(fallDistance);
if (playerIsOnPlatform)
{
player.transform.Translate(fallDistance);
}
}
}

Playing a 2d animation before flipping a sprite in Unity c#

I was actually able to do this with an enemy but for some reason I can't get it to work if it's the player.
See, the player is in a default, idle animation. When I press the arrow key from the opposite direction its facing at (default is the right when game starts -->), I want it to play a turning animation before the sprite flips over its x scale.
However what it's doing right now when I press the arrow key to turn him, is that firstly, it quickly flips the sprite over, then performs the animation as if it hadn't been flipped yet, then flips over to the other direction again.
In my animator, the idle has no exit time to the flip node and the flip node does have an exit time back to idle, just in case you would inquire. I've tried invoking a timer here and there as well but so far no luck. Can anyone help please?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class tulMoveMount : MonoBehaviour {
private Animator anim;
private Rigidbody2D rb;
public Image manaBar;
public LayerMask whatIsGround;
private bool grounded = false;
public Transform groundCheck;
public float groundCheckRadius;
private bool goRight = true;
private bool jump;
private bool turn = false;
private bool idle = true;
private bool mountOff;
private bool turnComplete = false;
public float runSpeed;
public float walkSpeed;
private float move;
public float turnDelay = 2.25f;
public float timer3 = 2.26f;
void Start ()
{
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
}
void Update ()
{
grounded = Physics2D.OverlapCircle (groundCheck.position, groundCheckRadius, whatIsGround);
timer -= Time.deltaTime;
turnDelay -= Time.deltaTime;
HandleMovement ();
}
void HandleMovement()
{
float move = Input.GetAxis ("Horizontal");
float moveV = Input.GetAxis ("Vertical");
{
rb.velocity = new Vector2 (move * walkSpeed, rb.velocity.y);
anim.SetFloat ("walkSpeed", Mathf.Abs (move));
}
if (!goRight && move > 0) {
FlipConditions ();
Invoke ("ResetValues",timer3 );
Flip ();
turnComplete = false;
}
if (goRight && move < 0) {
FlipConditions ();
Invoke ("ResetValues",timer3 );
Flip ();
}
}
void FlipConditions()//
{
idle = false;
turn = true;
anim.SetTrigger ("turn");
idle = true;
anim.SetTrigger ("idle");
}
void Flip()
{
goRight = !goRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
turnComplete = false;
}
void ResetValues()
{
idle = true;
anim.SetTrigger ("idle");
}
}
You can try to flip the sprite in LateUpdate() after you perform perform any animation in Update(). Try something like that, placing the animation in Update:
// store references to components on the gameObject
Transform _transform;
Rigidbody2D _rigidbody;
// hold player motion in this timestep
float vx;
float vy;
float MoveSpeed;
void Awake () {
// get a reference to the components we are going to be changing and store a reference for efficiency purposes
transform = GetComponent<Transform> ();
rigidbody = GetComponent<Rigidbody2D> ();
}
// this is where most of the player controller magic happens each game event loop
void Update()
{
// determine horizontal velocity change based on the horizontal input
vx = Input.GetAxisRaw ("Horizontal");
// get the current vertical velocity from the rigidbody component
vy = rigidbody.velocity.y;
// Change the actual velocity on the rigidbody
rigidbody.velocity = new Vector2(vx * MoveSpeed, vy);
}
// Checking to see if the sprite should be flipped
// this is done in LateUpdate since the Animator may override the localScale
// this code will flip the player even if the animator is controlling scale
void LateUpdate()
{
// get the current scale
Vector3 localScale = transform.localScale;
if (vx > 0) // moving right so face right
{
facingRight = true;
} else if (vx < 0) { // moving left so face left
facingRight = false;
}
// check to see if scale x is right for the player
// if not, multiple by -1 which is an easy way to flip a sprite
if (((facingRight) && (localScale.x<0)) || ((!facingRight) && (localScale.x>0))) {
localScale.x *= -1;
}
// update the scale
transform.localScale = localScale;
}

2d standard assets prefab characterRobotBoy jumped into the boxCollider

I am using the standard 2d assets to learn developing 2d game with Unity, and I place a sprite with box-collider-2d, and choose the default standard assets CharacterRobotBoy to mess around with.
But I find that if I jumped and it's highly likely that the character will jump into the sprite which was intended to be made as a ground, but this will not happen every time. hope could get some help with that.
find the problem hard to describe and upload a video on youtue
EDIT
will just paste the script from the demo asset as required.
File PlatformerCharacter2D.cs
using System;
using UnityEngine;
namespace UnityStandardAssets._2D
{
public class PlatformerCharacter2D : MonoBehaviour
{
[SerializeField] private float m_MaxSpeed = 10f; // The fastest the player can travel in the x axis.
[SerializeField] private float m_JumpForce = 400f; // Amount of force added when the player jumps.
[Range(0, 1)] [SerializeField] private float m_CrouchSpeed = .36f; // Amount of maxSpeed applied to crouching movement. 1 = 100%
[SerializeField] private bool m_AirControl = false; // Whether or not a player can steer while jumping;
[SerializeField] private LayerMask m_WhatIsGround; // A mask determining what is ground to the character
private Transform m_GroundCheck; // A position marking where to check if the player is grounded.
const float k_GroundedRadius = .2f; // Radius of the overlap circle to determine if grounded
private bool m_Grounded; // Whether or not the player is grounded.
private Transform m_CeilingCheck; // A position marking where to check for ceilings
const float k_CeilingRadius = .01f; // Radius of the overlap circle to determine if the player can stand up
private Animator m_Anim; // Reference to the player's animator component.
private Rigidbody2D m_Rigidbody2D;
private bool m_FacingRight = true; // For determining which way the player is currently facing.
private void Awake()
{
// Setting up references.
m_GroundCheck = transform.Find("GroundCheck");
m_CeilingCheck = transform.Find("CeilingCheck");
m_Anim = GetComponent<Animator>();
m_Rigidbody2D = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
m_Grounded = false;
// The player is grounded if a circlecast to the groundcheck position hits anything designated as ground
// This can be done using layers instead but Sample Assets will not overwrite your project settings.
Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
m_Grounded = true;
}
m_Anim.SetBool("Ground", m_Grounded);
// Set the vertical animation
m_Anim.SetFloat("vSpeed", m_Rigidbody2D.velocity.y);
}
public void Move(float move, bool crouch, bool jump)
{
// If crouching, check to see if the character can stand up
if (!crouch && m_Anim.GetBool("Crouch"))
{
// If the character has a ceiling preventing them from standing up, keep them crouching
if (Physics2D.OverlapCircle(m_CeilingCheck.position, k_CeilingRadius, m_WhatIsGround))
{
crouch = true;
}
}
// Set whether or not the character is crouching in the animator
m_Anim.SetBool("Crouch", crouch);
//only control the player if grounded or airControl is turned on
if (m_Grounded || m_AirControl)
{
// Reduce the speed if crouching by the crouchSpeed multiplier
move = (crouch ? move*m_CrouchSpeed : move);
// The Speed animator parameter is set to the absolute value of the horizontal input.
m_Anim.SetFloat("Speed", Mathf.Abs(move));
// Move the character
m_Rigidbody2D.velocity = new Vector2(move*m_MaxSpeed, m_Rigidbody2D.velocity.y);
// If the input is moving the player right and the player is facing left...
if (move > 0 && !m_FacingRight)
{
// ... flip the player.
Flip();
}
// Otherwise if the input is moving the player left and the player is facing right...
else if (move < 0 && m_FacingRight)
{
// ... flip the player.
Flip();
}
}
// If the player should jump...
if (m_Grounded && jump && m_Anim.GetBool("Ground"))
{
// Add a vertical force to the player.
m_Grounded = false;
m_Anim.SetBool("Ground", false);
m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
}
}
private void Flip()
{
// Switch the way the player is labelled as facing.
m_FacingRight = !m_FacingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
}
Script Platformer2DUserControl.cs
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
namespace UnityStandardAssets._2D
{
[RequireComponent(typeof (PlatformerCharacter2D))]
public class Platformer2DUserControl : MonoBehaviour
{
private PlatformerCharacter2D m_Character;
private bool m_Jump;
private void Awake()
{
m_Character = GetComponent<PlatformerCharacter2D>();
}
private void Update()
{
if (!m_Jump)
{
// Read the jump input in Update so button presses aren't missed.
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
}
private void FixedUpdate()
{
// Read the inputs.
bool crouch = Input.GetKey(KeyCode.LeftControl);
float h = CrossPlatformInputManager.GetAxis("Horizontal");
// Pass all parameters to the character control script.
m_Character.Move(h, crouch, m_Jump);
m_Jump = false;
}
}
}

Npc animation following player unity 2d top down

Hey I am making a top down game in unity. The problem I ma having is making npc players change the way they are facing while following the player. So if the player turns left the npc follows them but doesn't turn to face the direction the npc is going. I can get the npc to look like its walking just not change the direction it is looking. This is a 2d top down game please any help will be nice. here is my npc code.
using UnityEngine;
using System.Collections;
public class SlimeController : MonoBehaviour
{
public Transform Character; // Target Object to follow
public float speed = 0.1F; // Enemy speed
public float maxDist = 10.0f;
public float attackdistance = 3;
public float farenough;
private Vector3 directionOfCharacter;
private bool challenged = false;// If the enemy is Challenged to follow by the player
public Transform StartMarker;
private Vector3 goback;
public Transform EndMarker;
public Rigidbody2D rb;
Animator anim;
float oldx;
bool left;
bool right;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
anim= GetComponent<Animator>();
oldx = transform.position.x;
}
void Update()
{
anim.SetBool("left", false);
anim.SetBool("right", false);
var distanceFromPlayer = Vector3.Distance(Character.position, transform.position);
if(oldx>transform.position.x)
{
left = false;
right = true;
}
if(oldx<transform.position.x)
{
left = true;
right = false;
}
if (oldx == transform.position.x)
{
left = false;
right = false;
}
if (challenged)
{
directionOfCharacter = Character.transform.position - transform.position;
directionOfCharacter = directionOfCharacter.normalized; // Get Direction to Move Towardsss
transform.Translate(directionOfCharacter * speed, Space.World);
enabled = true;
if (distanceFromPlayer < attackdistance)
{
attack();
}
if (distanceFromPlayer > attackdistance)
{
speed = 0.03f;
}
}
if (!challenged)
{
goback = StartMarker.transform.position - transform.position;
goback = goback.normalized;
transform.Translate(goback * speed, Space.World);
}
}
// Will be triggered as soon as player would touch the Enemy Object
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.name == ("Player"))
{
challenged = true;
}
}
private void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject.name == ("Player"))
{
speed = 0.03f;
challenged = false;
}
}
void attack()
{
speed = 0;
transform.Translate(directionOfCharacter * speed, Space.World);
}
}
This is because you are just moving the object towards your target. But to have it look at your target you need to also rotate it in the direction of your target.
The Transform Component has a function called LookAt. You supply it with your Target and the Axis your object should rotate around. So in your case:
this.transform.LookAt(Character, Vector3.up);
See here for more info on LookAt.

Categories

Resources