Moving Platforms - c#

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

Related

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;
}
}
}

Unity collider touch not act on player

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.

How can I replace characterScale.x = -1 with transform.Rotate (0f, 180f, 0f) in this context, without it being executed every frame?

I am very new to coding video games so I have been using a lot on online tutorials to assist me with making a basic platformer/shooter. In order for my character to be able to shoot in both directions, I need the sprite as well as it's child "FirePoint" to flip. How can I flip my character and it's children whenever the Horizontal value = -1 without the same command being executed every frame.
Thanks in advance!
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed;
public float jumpforce;
private float moveInput;
private Rigidbody2D rb;
private bool isGrounded;
public Transform groundCheck;
public float checkRadius;
public LayerMask whatIsGround;
private int extraJumps;
public int extraJumpsValue;
public Animator animator;
void Start()
{
extraJumps = extraJumpsValue;
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
}
void Update()
{
animator.SetFloat("Horizontal", moveInput);
if (Input.GetKeyDown(KeyCode.Space) && extraJumps > 0)
{
rb.velocity = Vector2.up * jumpforce;
extraJumps--;
}
else if (Input.GetKeyDown(KeyCode.Space) && extraJumps == 0 && isGrounded == true)
{
rb.velocity = Vector2.up * jumpforce;
}
if (isGrounded == true)
{
extraJumps = extraJumpsValue;
}
Vector3 characterScale = transform.localScale;
if (Input.GetAxisRaw("Horizontal") < 0)
{
characterScale.x = -1;
}
if (Input.GetAxisRaw("Horizontal") > 0)
{
characterScale.x = 1;
}
transform.localScale = characterScale;
}
}

How to change default attack direction for player?

I coded my player in my platform game so that he would attack with a sword when you press space. It attacks right when I run right. It attacks left when I run left. But when I stand still by default it attacks left. How do I make it attack right instead?
Below is all the code in my player controller script, and also an image of my blend tree.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public int moveSpeed;
private Animator anim;
public int playerJumpPower = 1250;
private float moveX;
public bool isGrounded;
public float fJumpWaitTime = 0.2f;
private float fJumpWait;
private object col;
private bool attacking;
public float attackTime;
private float attackTimeCounter;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (!attacking)
{
if (Input.GetButtonDown("Jump"))
{
Jump();
}
if (Input.GetAxisRaw("Horizontal") > 0.5f || Input.GetAxisRaw("Horizontal") < -0.5f)
{
transform.Translate(new Vector3(Input.GetAxisRaw("Horizontal") * moveSpeed * Time.deltaTime, 0f, 0f));
}
void Jump()
{
//Jumping Code
GetComponent<Rigidbody2D>().AddForce(Vector2.up * playerJumpPower);
isGrounded = false;
}
void OnCollisionEnter2D(Collision2D col)
{
Debug.Log("Player has collided with " + col.collider.name);
if (col.gameObject.tag == "ground")
{
isGrounded = true;
}
}
}
anim.SetFloat("MoveX", Input.GetAxisRaw("Horizontal"));
if (Input.GetKeyDown(KeyCode.Space))
{
attackTimeCounter = attackTime;
attacking = true;
anim.SetBool("Attack", true);
}
if(attackTimeCounter > 0)
{
attackTimeCounter -= Time.deltaTime;
}
if(attackTimeCounter <= 0)
{
attacking = false;
anim.SetBool("Attack", false);
}
}
}
After having another look at your Blend Tree, I would check if your Threst is the problem.
What you have right now:
PlayerAttackLeft 0 -1
PlayerAttackRight 1 1
What you should probably have:
PlayerAttackLeft -0.01 -1
PlayerAttackRight 0 1

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
}

Categories