Unity collider touch not act on player - c#

I have both player and ground with colliders 2D and player is supposed to stop on top of ground but instead it stops at the bottom of the ground.
Code
PlayerController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
private float moveSpeedStore;
public float speedMultiplier;
public float speedIncreateMilestone;
private float speedIncreateMilestoneStore;
private float speedMilestoneCount;
private float speedMilestoneCountStore;
public float jumpForce;
public float jumpTime;
private float jumpTimeCounter;
private bool stoppedJumping;
private bool canDoubleJump;
private Rigidbody2D myRigidbody;
public bool grounded;
public LayerMask whatIsGround;
public Transform groundCheck;
public float groundCheckRadius;
// private Collider2D myCollider;
private Animator myAnimator;
public GameManager theGameManager;
public AudioSource jumpSound;
public AudioSource deathSound;
// Start is called before the first frame update
void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
myAnimator = GetComponent<Animator>();
jumpTimeCounter = jumpTime;
speedMilestoneCount = speedIncreateMilestone;
moveSpeedStore = moveSpeed;
speedMilestoneCountStore = speedMilestoneCount;
speedIncreateMilestoneStore = speedIncreateMilestone;
stoppedJumping = true;
}
// Update is called once per frame
void Update()
{
grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
if(transform.position.x > speedMilestoneCount)
{
speedMilestoneCount += speedIncreateMilestone;
speedIncreateMilestone = speedIncreateMilestone * speedMultiplier;
moveSpeed = moveSpeed * speedMultiplier;
}
myRigidbody.velocity = new Vector2(moveSpeed, myRigidbody.velocity.y);
if(Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0) )
{
if(grounded)
{
myRigidbody.velocity = new Vector2(myRigidbody.velocity.x, jumpForce);
stoppedJumping = false;
jumpSound.Play();
}
if(!grounded && canDoubleJump)
{
myRigidbody.velocity = new Vector2(myRigidbody.velocity.x, jumpForce);
jumpTimeCounter = jumpTime;
stoppedJumping = false;
canDoubleJump = false;
jumpSound.Play();
}
}
if((Input.GetKey(KeyCode.Space) || Input.GetMouseButton(0)) && !stoppedJumping)
{
if(jumpTimeCounter > 0)
{
myRigidbody.velocity = new Vector2(myRigidbody.velocity.x, jumpForce);
jumpTimeCounter -= Time.deltaTime;
}
}
if(Input.GetKeyUp(KeyCode.Space) || Input.GetMouseButtonUp(0))
{
jumpTimeCounter = 0;
stoppedJumping = true;
}
if(grounded)
{
jumpTimeCounter = jumpTime;
canDoubleJump = true;
}
myAnimator.SetFloat("Speed", myRigidbody.velocity.x);
myAnimator.SetBool("Grounded", grounded);
}
void OnCollisionEnter2D(Collision2D other) {
if(other.gameObject.tag == "killbox")
{
theGameManager.RestartGame();
moveSpeed = moveSpeedStore;
speedMilestoneCount = speedMilestoneCountStore;
speedIncreateMilestone = speedIncreateMilestoneStore;
deathSound.Play();
}
}
}
Player settings
Question
What should I do to hold my player on top of ground?
NOTE: it's my first question on unity ever so if you need any sort of code or data please just ask, I try my best to provide you what you need.
Thanks.

It looks like your collider is simply too high. You'll notice that the green box indicating your collider size and position is colliding with the correct spot on the ground. The bottom of it is just touching the top of the ground. You simply need to move the collider down on the player so that the bottom of the green box is at the bottom of the player's sprite.

Related

Moving an object towards a position not working properly

I have written a code to get a random transform from my list pathPoints and move my object based on that transform, but what it is doing is getting multiple transforms and trying to move everywhere at once. I want the object to move at one position then get a new position and move there then repeat.
Here is the code:-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PathFinder : MonoBehaviour
[SerializeField] List<Transform> pathPoints;
[SerializeField] Transform pathPrefab;
[SerializeField] float moveSpeed = 10f;
[SerializeField] bool isMoving = false;
[SerializeField] bool isH_Attacking = false;
Animator anim;
Transform defaultWayPoint;
Transform currentTargetPoint;
void Awake()
{
anim = GetComponent<Animator>();
defaultWayPoint = pathPrefab.GetChild(0);
}
void Start()
{
currentTargetPoint = pathPoints[Random.Range(0, pathPoints.Count)];
transform.position = defaultWayPoint.position;
}
void MoveToNextWayPoint()
{
if(transform.position != currentTargetPoint.position)
{
float delta = moveSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, currentTargetPoint.position, delta);
anim.SetBool("isMoving", true);
isMoving = true;
}
GetNextWayPoint();
}
Transform GetNextWayPoint()
{
currentTargetPoint = pathPoints[Random.Range(0, pathPoints.Count)];
Debug.Log(currentTargetPoint.position);
return currentTargetPoint;
}
void Update()
{
MoveToNextWayPoint();
}
*The script is attached to the gameObject which I want to move.
*This is a 2d project.
void MoveToNextWayPoint()
{
if(transform.position != currentTargetPoint.position)
{
float delta = moveSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, currentTargetPoint.position, delta);
anim.SetBool("isMoving", true);
isMoving = true;
}
else
{
GetNextWayPoint();
}
}

how can I make the game object disappear?

when I was watching on YouTube, tutorials about endless runner on part 2, the game object wouldn't disappear when it hits the player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Obstacle : MonoBehaviour
{
public int damage = 1;
public float speed;
private void Update()
{
transform.Translate(Vector2.left * speed * Time.deltaTime);
}
void onTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("rocket"))
{
//rocket takes damage 1
other.GetComponent<rocket>().health -= damage;
Debug.Log(other.GetComponent<rocket>().health);
Destroy(gameObject);
}
}
}
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class rocket : MonoBehaviour
{
private Vector2 targetPos;
public float Yincrement;
public float speed;
public float maxHeight;
public float minHeight;
public int health = 3;
void Update()
{
if (health <= 0)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.UpArrow) && transform.position.y < maxHeight)
{
targetPos = new Vector2(transform.position.x, transform.position.y + Yincrement);
}
else if (Input.GetKeyDown(KeyCode.DownArrow) && transform.position.y > minHeight)
{
targetPos = new Vector2(transform.position.x, transform.position.y - Yincrement);
}
}
}
from this one https://www.youtube.com/watch?v=FVCW5189evI and I'm confused why it didn't work, can someone tell me what is wrong?
if you want to destroy use this, Correct Method to get the game object when collide is: other.gameObject
void onTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("rocket"))
{
//rocket takes damage 1
other.gameObject.GetComponent<rocket>().health -= damage;
Debug.Log(other.gameObject.GetComponent<rocket>().health);
Destory(other.gameObject);
}
}
public class megaStar : MonoBehaviour{
private Rigidbody2D rb;
private Animator _ani;
public bool canAttack = true;
[SerializeField] private Attack _attackObject;
private AudioSource _as;
public checkpoint lastCheckpoint;
public bool isDead = false;
private float _timer = 1.0f;
public float attackTimer = 2.0f;
public GameObject projectile;
public float projectileSpeed = 18.0f;
public Transform projectileAttackPoint;
public float timeDelayForNextShoot = 0.1f;
private float CONST_timeDelayForNextShoot;
// Start is called before the first frame update
void Start(){
CONST_timeDelayForNextShoot = timeDelayForNextShoot;
rb = GetComponent<Rigidbody2D>();
_as = GetComponent<AudioSource>();
_ani = GetComponent<Animator>();
_timer = attackTimer;
}
void Update(){
if (Input.GetKey(KeyCode.W))
{
rb.velocity = new Vector2(0f, 10f);
}
else if (Input.GetKey(KeyCode.S))
{
rb.velocity = new Vector2(0f, -10f);
}
else
{
rb.velocity = new Vector2(0f, 0f);
}
timeDelayForNextShoot -= Time.deltaTime;
if (Input.GetKeyDown(KeyCode.K) && timeDelayForNextShoot <= 0f){
_ani.SetBool("projectileAttack", true);
GameObject go = Instantiate(projectile, projectileAttackPoint.position, projectileAttackPoint.rotation) as GameObject;
go.GetComponent<Rigidbody2D>().velocity = new Vector2(-projectileSpeed, 0.0f);
Destroy(go, 2.0f);
timeDelayForNextShoot = CONST_timeDelayForNextShoot;
canAttack = false;
// new WaitForSeconds(1);
return;
}
}
void FixedUpdate()
{
if (!isDead)
{
Update();
}
else{
rb.velocity = Vector2.zero;
RigidbodyConstraints2D newRB2D = RigidbodyConstraints2D.FreezePositionY;
rb.constraints = newRB2D;
}
}
private void OnCollisionEnter2D(Collision2D collision){
if (collision.gameObject.CompareTag("Enemy"))
{
GetComponent<HitPoints>().TakeDamage(1);
}
}
}
Use SetActive instead of Destroy Function.
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("rocket"))
{
//rocket takes damage 1
other.gameObject.GetComponent<rocket>().health -= damage;
Debug.Log(other.gameObject.GetComponent<rocket>().health);
gameObject.SetActive(false);// it'll Hide GameObject instead of Destroying
// gameObject.SetActive(true);// to show again
}
}

Experiencing a weird collision bug between box colliders and tilemaps

This is my player movement code:
Footage of bug and inspector elements:
https://imgur.com/a/bmGqL1M
As you can see in this Imgur video, for some reason my player character, and also a pushable crate, can clip into this tilemap for a few pixels. I'm not quite sure why this is happening, since I've added a composite collider2D to the tilemap, to get rid of the very common "getting stuck in tilemap" bug, which isn't the case here, the clipping doesn't actually alter the movement in any way.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[Header("Movement")]
[SerializeField] private float movementSpeed;
[SerializeField] private float jumpForce;
[Header("Jumping")]
private bool isGrounded;
[SerializeField] private Transform feetPos;
[SerializeField] private float checkRadius;
[SerializeField] private LayerMask whatIsGround;
[SerializeField] private float hangTime;
private float hangCounter;
private Rigidbody2D rb;
private SpriteRenderer sr;
private float moveX;
void Start()
{
rb = GetComponent<Rigidbody2D>();
sr = GetComponent<SpriteRenderer>();
}
void Update()
{
GetInput();
BetterJump();
}
void BetterJump()
{
isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);
if (isGrounded)
{
hangCounter = hangTime;
} else
{
hangCounter -= Time.deltaTime;
}
if (hangCounter > 0 && Input.GetKeyDown(KeyCode.Space))
{
rb.velocity = Vector2.up * jumpForce;
}
if (Input.GetButtonUp("Jump") && rb.velocity.y > 0)
{
rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * .5f);
}
}
void FixedUpdate()
{
Move();
}
void Move()
{
rb.position += new Vector2(moveX, 0) * Time.deltaTime * movementSpeed;
}
void GetInput()
{
moveX = Input.GetAxisRaw("Horizontal");
if(moveX < 0)
{
sr.flipX = true;
}
else if (moveX > 0)
{
sr.flipX = false;
}
}
}

I'm trying to make my 2D unity character jump

So as I said, I'm trying to make my character jump in Unity, but nothing is happening when I hit space, and Unity isn't throwing any errors.
public class Player : MonoBehaviour
{
private Rigidbody2D myRigidbody;
[SerializeField]
public float jumpSpeed;
private Animator myAnimator;
[SerializeField]
private float movementSpeed;
private bool facingLeft;
[SerializeField]
private Transform[] groundPoints;
[SerializeField]
private float groundRadius;
[SerializeField]
private LayerMask whatIsGround;
private bool isGrounded;
private bool jump;
[SerializeField]
private float jumpForce;
// Start is called before the first frame update
void Start()
{
facingLeft = true;
myRigidbody = GetComponent<Rigidbody2D>();
myAnimator = GetComponent<Animator>();
}
// Update is called once per frame
void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
Debug.Log(horizontal);
isGrounded = IsGrounded();
HandleMovement(horizontal);
flip(horizontal);
}
private void HandleMovement(float horizontal)
{
myRigidbody.velocity = new Vector2(horizontal * movementSpeed, myRigidbody.velocity.y);
myAnimator.SetFloat("speed", Mathf.Abs(horizontal));
if (isGrounded && jump)
{
isGrounded = false;
myRigidbody. AddForce(new Vector2(0, jumpForce));
}
}
private void HandleInput()
{
if (Input.GetKeyDown(KeyCode.Space))
{
jump = true;
}
}
private void flip(float horizontal)
{
if (horizontal < 0 && !facingLeft || horizontal > 0 && facingLeft)
{
facingLeft = !facingLeft;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
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;
}
}
I've been following this tutorial for it, and his is jumping, but mine isn't. I think it might have something to do with the way I have the groundpoints set up, but I'm not sure if it's a error in the code or if it's in Unity.
You are not calling HandleInput anywhere.
add to fixed update
void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
Debug.Log(horizontal);
isGrounded = IsGrounded();
HandleMovement(horizontal);
flip(horizontal);
HandleInput(); // add this so you are sampling input
}

Moving Platforms

We are at very beginning of studying Unity, so we decided to create a mini-platformer. We've already made coins, platforms and character animation, but when we tried to animate a platform, a huge catastrophe appeared. The problem is that character can't stand on the platform. When the platform moves, he falls (it looks like there's no friction, but we tried to set one - it was helpless).
Maybe, we repeat the question, that have been asked before, but hope you'll help us to solve this paradox. Have a nice day ;)
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class CharControl : MonoBehaviour
{
public float maxSpeed = 10f;
private bool isFacingRight = true;
private Animator anim;
private bool isGrounded = false;
public Transform groundCheck;
private float groundRadius = 0.2f;
public LayerMask whatIsGround;
public Text scoreText;
public float score = 0;
private void Start()
{
anim = GetComponent<Animator>();
}
private void FixedUpdate()
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
anim.SetBool ("Ground", isGrounded);
anim.SetFloat ("vSpeed", rigidbody2D.velocity.y);
if (isGrounded && rigidbody2D.velocity.y != 0)
return;
float move = Input.GetAxis("Horizontal");
anim.SetFloat("Speed", Mathf.Abs(move));
rigidbody2D.velocity = new Vector2(move * maxSpeed, rigidbody2D.velocity.y);
if(move > 0 && !isFacingRight)
Flip();
else if (move < 0 && isFacingRight)
Flip();
}
private void Update()
{
if (isGrounded && (Input.GetKeyDown (KeyCode.Space) || Input.GetKeyDown(KeyCode.Joystick1Button0)))
{
anim.SetBool("Ground", false);
rigidbody2D.AddForce(new Vector2(0, 600));
}
}
private void Flip()
{
isFacingRight = !isFacingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
void OnTriggerEnter2D(Collider2D col){
if(col.gameObject.name == "Skull"){
score++;
Destroy (col.gameObject);
scoreText.text = "" + score;
}
if ((col.gameObject.name == "dead"))
Application.LoadLevel (Application.loadedLevel);
}}
you need to set MovingPlatform is ParentObject of HoldPlayerPlatform.
check below images for that also
Here is Holding Player Script on Moving Platform.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HoldPlayer : MonoBehaviour
{
private GameObject target = null;
private Vector3 offset;
void Start()
{
target = null;
}
void OnTriggerStay(Collider col)
{
target = col.gameObject;
offset = target.transform.position - transform.position;
}
void OnTriggerExit(Collider col)
{
target = null;
}
void LateUpdate()
{
if (target != null)
{
target.transform.position = transform.position + offset;
}
}
}
Here is image for setup HoldPlayerPlatform
Here is Setup for MovingPlatform

Categories