Why are collision checks in Unity2D providing various outcomes? - c#

I'm trying to recreate AA in Unity2D to kind of learn how everything works, I'm using a YouTube tutorial to guide me through it and I have the exact code in the video but it doesn't seem to be working correctly, the pins won't stop at the same time when they touch the rotating ball (seen below). Some will go halfway into the ball while others will stop prematurely.
Here's the pin code (Pin.cs):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pin : MonoBehaviour {
private bool moving = true;
public float speed = 20f;
public Rigidbody2D rb;
void Update() {
if (moving)
rb.MovePosition(rb.position + Vector2.up * speed * Time.deltaTime);
}
void OnTriggerEnter2D(Collider2D collider) {
if (collider.tag == "Rotator") {
moving = false;
transform.SetParent(collider.transform);
}
}
}

Just use FixedUpdate() instead Update().
Refer to Unity Documentation - FixedUpdate link, FixedUpdate() should be used instead of Update() when dealing with Rigidbody.
So, Change your code to this:
public class Pin : MonoBehaviour
{
...
void FixedUpdate()
{
if (moving)
rb.MovePosition(rb.position + Vector2.up * speed * Time.deltaTime);
}
void OnTriggerEnter2D(Collider2D collider)
{
...
}
}
I hope it helps you.

Related

Sprites wont detect collision

Sorry for the bad formatting I don't know how to do this. I'm using 2020.3.21f1 and following a tutorial and when the enemy circle hits the player he doesn't take damage. when they collide they don't overlap at all, but the Debug.log isn't registering either so I think that the circle collider 2D is the problem. the enemy sprite still moves towards the player when it is in range. another problem (that will turn into a feature if I cant figure out how to change it) is that when the enemy collides with the player and the player pushes it goes the direction it was pushed until it runs into something Here's the tutorial I'm following
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy: MonoBehaviour
{
public float speed = 3f;
private Transform target;
[SerializeField] private float attackDamage = -10f;
private void Update(){
if (target != null){
float step = speed*Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, target.position, step);
}
}
private void OnCollision(Collision2D other){
if (other.gameObject.tag == "player"){
Debug.Log("hit");
other.gameObject.GetComponent<PlayerHealth>().UpdateHealth(attackDamage);
}
}
private void OnTriggerEnter2D(Collider2D other) {
if(other.gameObject.tag == "Player"){
target = other.transform;
Debug.Log(target);
}
}
private void OnTriggerExit2D(Collider2D other) {
if(other.gameObject.tag == "Player"){
target = null;
Debug.Log(target);
}
}
}
The sprite by itself wont detect collision, you need to add a box collider for that. If you add that component to the player then modify your code to include those collision detections then it should function ad intended.:)
-TheHackintoshProgrammer;

Dashing in Unity 2D using the Rigidbody Component

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float movementSpeed;
public Rigidbody2D Rigidbody;
private Vector2 moveDirection;
public Transform Player;
void Start()
{
}
void Update()
{
ProcessInputs();
} void FixedUpdate()
{
move();
}
void ProcessInputs()
{
float moveX = Input.GetAxisRaw("Horizontal");
float moveY = Input.GetAxisRaw("Vertical");
moveDirection = new Vector2(moveX, moveY).normalized;
}
void move()
{
Rigidbody.velocity = new Vector2(moveDirection.x * movementSpeed, moveDirection.y * movementSpeed);
}
}
So i needed some tips so i thoght id ask here, i wanted to implement dashing in my Top-Down-Shooter but i didnt find any code on Youtube that would properly work with my code i have also tried moveing the players position +2 to the wanted direction but i couldnt work it out.
id be happy if yall could help me.
Nice that you are using FixedUpdate() for physics - many beginners use that wrong.
However do not set velocity manually. Use AddForce.
It will effectively set the velocity but automatically takes the objects mass into account and allows to speed up instead of instantly being at speed.
That is the more logical approach since you move in a direction by applying forces to your body.
For Dashing, you could add a significantly higher force for a small number of Physics frames (aka small number of FixedUpdate calls). You can use a countdown which you set to a number when the chaarcter hsould start dashing.
In the FixedUpdate you decrement the counter and as long as it is >0 you apply the dashing force.

How can I make the two cubes to stop when colliding?

Or making them bounce when colliding. but now it's not detecting any collision.
The first cube have a Rigidbody Use Gravity and Is Kinematic both checked enabled true.
If I will disable the Is Kinematic the cube will fall down.
Both cubes have attached the same script.
Both cubes have a box collider and the Is Trigger on both is unchecked disabled.
This script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Door : MonoBehaviour
{
public Transform target;
public float speed;
private void Start()
{
}
private void Update()
{
float step = speed * Time.deltaTime; // calculate distance to move
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
}
}
Each cube have the script and target is the other cube. So both cubes are moving to each other but never collide.
Both cubes settings screenshot :
It would be better practice set rigidbody.velocity once instead of changing transform.position every frame, but this solution should work regardless:
private bool collided = false;
private void Move() {
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
}
private void Update() {
if (!collided) {
Move();
}
}
private void OnCollisionEnter(Collider other) {
if (other.gameObject.GetComponent<Door>() != null) {
collided = true;
}
}
This may not be the best way to do it depending on how you plan on moving forward, but this is a way that works.
If you want to make them bounce, I'd suggest using rigidbody.AddForce() or set rigidbody.velocity. Then you can either use a bouncy physic material or changing the OnCollisionEnter code to use rigidbody.AddForce() or rigidbody.velocity when they collide with each other.

Moving a rigid body in the direction it's facing in Unity and C#

I've been trying to get this working using pretty much every method I can find (even using the dreaded transform.translate) but I just can't seem to get it working. This is just a draft of the code and if there are any other ways to go about it I'm down to change some stuff.
Currently, he barely moves (it looks like he's getting stuck on the floor somehow.) I'm fairly new to moving objects using rigid bodies so I'm pretty much in the dark on how to solve this issue.
Here's the script from my latest crack at it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerTest : MonoBehaviour
{
public float speed = 10.0f;
public Rigidbody rb;
public Vector3 movement;
// Start is called before the first frame update
void Start()
{
rb.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("w"))
{
movement = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
}
}
void FixedUpdate()
{
moveCharacter(movement);
}
void moveCharacter(Vector3 direction)
{
rb.MovePosition(transform.position + (transform.forward * speed * Time.deltaTime));
}
}
In your code you have your moveCharacter function inside your Update function, enclosed is the fixed one, which should work now. Before your FixedUpdate was not getting called, therefore your moveCharacter function was not as well and your GameObject was not moving.
EDIT 1: You shoud also multiply with your movement direction as well, updated the script to fit that
EDIT 2: I misplaced the curly brackets, fixed that now
EDIT 3: You should also update your movement Vector3 every frame, not if W is pressed, fixed the script again.
EDIT 4: Fixed the movement bug (copy and paste entire script, since i changed more lines)
This is the updated script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerTest : MonoBehaviour
{
public float speed = 10.0f;
public Rigidbody rb;
public Vector3 movement;
// Start is called before the first frame update
void Start()
{
rb.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
movement = new Vector3(Input.GetAxis("Horizontal"), 1f, Input.GetAxis("Vertical"));
}
void FixedUpdate()
{
moveCharacter(movement);
}
void moveCharacter(Vector3 direction)
{
Vector3 offset = new Vector3(movement.x * transform.position.x, movement.y * transform.position.y, movement.z * transform.position.z);
rb.MovePosition(transform.position + (offset * speed * Time.deltaTime));
}
}
References: Rigidbody.MovePosition

How to solve problem with nojump object, that has to jump?

I have problem with my code, I´ve started learn C#, so I tried code some game(something like Geometry Dash). I want that move and on click jump. I wrote "move code" and "onclick jump code" but isn´t working.
I´m writing in Microsoft Visual Studio in C# and design in Unity 2018.3.5f1.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Plaxercontrol2 : MonoBehaviour
{
public Rigidbody2D rb;
public Transform groundCheck;
public Transform startPosition;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool onGround;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
rb.velocity = new Vector2(3, rb.velocity.y);
onGround = Physics2D.OverlapCircle(groundCheck.position,
groundCheckRadius, whatIsGround);
if (Input.GetMouseButtonDown(0) && onGround)
{
rb.velocity = new Vector2(5, rb.velocity.x);
}
}
}
Now, it´s only moving
and picture of Unity
Instead of changing yourself the velocity, I'm pretty sure you should use rb.AddForce() or something similar. That is how you're supposed to move rigid bodies.
You could do something like:
rb.AddForce(Vector2.up * whatEverValue, ForceMode2D.Impulse)

Categories

Resources