Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 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 /
  • Help Room /
avatar image
0
Question by jeff.teoh · Jun 23, 2016 at 12:51 AM · 2d game2d-platformercamera-movementcamera follow

Camera not following 2D character when the character reaches the ground.

Hi, I have a problem with my camera and that is that it does not follow the character when the character reaches the ground. The camera follows the character if the character is above the ground but it does not when it reaches the ground.

alt text

alt text

Player script: using UnityEngine; using System.Collections; using System;

public delegate void DeadEventHandler();

public class Player : Character { private static Player instance;

 private IUseable useable;

 private int coins;

 [SerializeField]
 private float climbSpeed;

 private Vector2 startPos;

 public event DeadEventHandler Dead;

 [SerializeField]
 private Transform[] groundPoints;

 [SerializeField]
 private float groundRadius;

 [SerializeField]
 private LayerMask whatIsGround;

 [SerializeField]
 private bool airControl;

 [SerializeField]
 private float jumpForce;

 private bool immortal = false;

 private SpriteRenderer spriteRenderer;

 [SerializeField]
 private float immortalTime;

 private float direction;

 private bool move;

 private float btnHorizontal;

 public Rigidbody2D MyRigidbody { get; set; }

 public bool Slide { get; set; }

 public bool Jump { get; set; }

 public bool OnGround { get; set; }

 public bool OnLadder { get; set; }

 public static Player Instance
 {
     get
     {
         if (instance == null)
         {
             instance = GameObject.FindObjectOfType<Player>();
         }
         return instance;
     }
 }

 public override bool IsDead
 {
     get
     {
         if (healthStat.CurrentValue <= 0)
         {
             OnDead();
         }

         return healthStat.CurrentValue <= 0;
     }
 }

 // Use this for initialization
 public override void Start()
 {
     base.Start();
     startPos = transform.position;
     spriteRenderer = GetComponent<SpriteRenderer>();
     MyRigidbody = GetComponent<Rigidbody2D>();
 }

 void Update()
 {
     if (!TakingDamage && !IsDead)
     {
         if (transform.position.y <= -14f)
         {
             Death();

         }
         HandleInput();
     }

 }

 // Update is called once per frame
 void FixedUpdate()
 {
     if (!TakingDamage && !IsDead)
     {
         float horizontal = Input.GetAxis("Horizontal");

         float vertical = Input.GetAxis("Vertical");

         OnGround = IsGrounded();

         if (move)
         {
             this.btnHorizontal = Mathf.Lerp(btnHorizontal, direction, Time.deltaTime * 2);
             //HandleMovement(btnHorizontal);
             Flip(direction);
         }
         else
         {
             HandleMovement(horizontal,vertical);

             Flip(horizontal);
         }



         HandleLayers();
     }

 }


 private void Use()
 {
     if (useable != null)
     {
         useable.Use();
     }
 }

 public void OnDead()
 {
     if (Dead != null)
     {
         Dead();
     }
 }



 private void HandleMovement(float horizontal, float vertical)
 {
     if (MyRigidbody.velocity.y < 0)
     {
         MyAnimator.SetBool("land", true);
     }
     if (!Attack && !Slide && (OnGround || airControl))
     {
         MyRigidbody.velocity = new Vector2(horizontal * movementSpeed, MyRigidbody.velocity.y);
     }
     if (Jump && MyRigidbody.velocity.y == 0 && !OnLadder)
     {
         MyRigidbody.AddForce(new Vector2(0, jumpForce));
     }
     if (OnLadder)
     {
         MyAnimator.speed = vertical != 0 ? Mathf.Abs(vertical) : Mathf.Abs(horizontal);
         MyRigidbody.velocity = new Vector2(horizontal * climbSpeed, vertical * climbSpeed);
     }

     MyAnimator.SetFloat("speed", Mathf.Abs(horizontal));
 }

 private void HandleInput()
 {
     if (Input.GetKeyDown(KeyCode.Space) && !OnLadder)
     {
         MyAnimator.SetTrigger("jump");
         Jump = true;
     }
     if (Input.GetKeyDown(KeyCode.LeftShift))
     {
         MyAnimator.SetTrigger("attack");
     }
     if (Input.GetKeyDown(KeyCode.LeftControl))
     {
         MyAnimator.SetTrigger("slide");
     }
     if (Input.GetKeyDown(KeyCode.V))
     {
         MyAnimator.SetTrigger("throw");
     }
     if (Input.GetKeyDown(KeyCode.E))
     {
         Use();
     }
 }

 private void Flip(float horizontal)
 {
     if (horizontal > 0 && !facingRight || horizontal < 0 && facingRight)
     {
         ChangeDirection();
     }
 }

 private bool IsGrounded()
 {
     if (MyRigidbody.velocity.y <= 0)
     {
         foreach (Transform point in groundPoints)
         {
             Collider2D[] colliders = Physics2D.OverlapCircleAll(point.position, groundRadius, whatIsGround);

             for (int i = 0; i < colliders.Length; i++)
             {
                 if (colliders[i].gameObject != gameObject)
                 {
                     return true;
                 }
             }

         }
     }
     return false;
 }



 private void HandleLayers()
 {
     if (!OnGround)
     {
         MyAnimator.SetLayerWeight(1, 1);
     }
     else
     {
         MyAnimator.SetLayerWeight(1, 0);
     }
 }

 public override void ThrowKnife(int value)
 {
     if (!OnGround && value == 1 || OnGround && value == 0)
     {
         base.ThrowKnife(value);
     }
 }

 private IEnumerator IndicateImmortal()
 {
     while (immortal)
     {
         spriteRenderer.enabled = false;

         yield return new WaitForSeconds(.1f);

         spriteRenderer.enabled = true;

         yield return new WaitForSeconds(.1f);
     }
 }

 public override IEnumerator TakeDamage()
 {
     if (!immortal)
     {
        healthStat.CurrentValue -= 10;

         if (!IsDead)
         {
             MyAnimator.SetTrigger("damage");
             immortal = true;

             StartCoroutine(IndicateImmortal());
             yield return new WaitForSeconds(immortalTime);

             immortal = false;
         }
         else
         {
             MyAnimator.SetLayerWeight(1, 0);
             MyAnimator.SetTrigger("die");
         }

     }
 }

 public override void Death()
 {
     MyRigidbody.velocity = Vector2.zero;
     MyAnimator.SetTrigger("idle");
     healthStat.CurrentValue = healthStat.MaxVal;
     transform.position = startPos;
 }

 public void BtnJump()
 {
     MyAnimator.SetTrigger("jump");
     Jump = true;
 }

 public void BtnAttack()
 {
     MyAnimator.SetTrigger("attack");
 }

 public void BtnSlide()
 {
     MyAnimator.SetTrigger("slide");
 }

 public void BtnTrow()
 {
     MyAnimator.SetTrigger("throw");
 }

 public void BtnMove(float direction)
 {
     this.direction = direction;
     this.move = true;
 }

 public void BtnStopMove()
 {
     this.direction = 0;
     this.btnHorizontal = 0;
     this.move = false;
 }

 public void OnCollisionEnter2D(Collision2D other)
 {
     if (other.gameObject.tag == "Coin")
     {
         GameManager.Instance.CollectedCoins++;
         Destroy(other.gameObject);
     }
 }

 public override void OnTriggerEnter2D(Collider2D other)
 {
     if (other.tag == "GameObject")
     {
         useable = other.GetComponent<IUseable>();
     }

     base.OnTriggerEnter2D(other);
 }

 public void OnTriggerExit2D(Collider2D other)
 {
     if (other.tag == "GameObject")
     {
         useable = null;
     }
 }

}

Camera follow script:

using UnityEngine; using System.Collections;

public class CameraFollow : MonoBehaviour {

 /// <summary>
 /// The maximum x position of the camera
 /// </summary>
 [SerializeField]
 private float xMax;

 /// <summary>
 /// The maximum y position of the camera
 /// </summary>
 [SerializeField]
 private float yMax;

 /// <summary>
 /// The minimum x position of the camera
 /// </summary>
 [SerializeField]
 private float xMin;

 /// <summary>
 /// The minimum y positoin of the amera
 /// </summary>
 [SerializeField]
 private float yMin;

 /// <summary>
 /// The target that the camera will follow
 /// </summary>
 private Transform target;

 // Use this for initialization
 void Start ()
 {
     //Sets the cameras target as the player
     target = GameObject.Find("Player").transform;
 }

 // Update is called once per frame
 void LateUpdate()
 {
     //Moves the camera to the target's position, while calamping it inside the level
     transform.position = new Vector3(Mathf.Clamp(target.position.x, xMin, xMax), Mathf.Clamp(target.position.y, yMin, yMax), transform.position.z);
 }

}

screen-shot-2016-06-23-at-101619-am.png (494.6 kB)
screen-shot-2016-06-23-at-102059-am.png (69.1 kB)
Comment
Add comment
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

0 Replies

· Add your reply
  • Sort: 

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

64 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

Related Questions

How to stop the camera when the player has reached the edge of the level? 2 Answers

How to set Camera Limits in Unity that would stay accurate for different screen ratios? 2 Answers

How to make a stationary camera into a moving camera that follows the player when entering a new scene? 0 Answers

2D Sample Camera Script malfunctioning 0 Answers

CineMachine Camera hangup on respawn 1 Answer


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