How to use Triggers as a Boundary? - c#

This code resets my camera(character) position if the user tries to exit the game boundaries by using a box collider and triggers. Would there be any way to stop the camera or bounce back the camera slightly when it enters/exits a trigger instead of resetting its position? Thank you
using UnityEngine;
using System.Collections;
public class BoundaryTrigger : MonoBehaviour {
public float hoverForce = 12f;
public Vector3 startPos;
void Start()
{
startPos = transform.position;
}
void OnTriggerEnter(Collider other) {
}
void OnTriggerStay(Collider other)
{
}
void OnTriggerExit(Collider other)
{
transform.position = startPos;
}
}

I would do something like this:
Vector3 m_LastValidPosition = null;
void OnTriggerStay(Collider other)
{
m_LastValidPosition = transform.position;
}
void OnTriggerExit(Collider other)
{
transform.position = m_LastValidPosition;
}

Related

Why object has a weird behavior in case of collision?

I have the problem with collision. Beginning creating the 3D game, I noticed that Player (gameObject) when moving in case of collision either falls down, or passes through the object, or repels from the object if it is inside it. I want to Player in case of collision couldn't pass through objects. Objects have colliders, Player has both collider, and Rigidbody with Physic Material. I'm beginner, so I don not know how to solve this problem. What is wrong?
Below script Player:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] public int speed;
public bool ground;
public float jumpPower = 2500f;
public Rigidbody rb;
void Start()
{
rb= GetComponent<Rigidbody>();
}
void Update()
{
GetInput();
}
private void GetInput()
{
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
{
transform.position += transform.forward * speed * Time.deltaTime;
}
// Movement Player...
if (Input.GetKeyDown(KeyCode.Space))
{
if (ground == true)
{
rb.AddForce(transform.up * jumpPower);
}
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Ground")
{
ground = true;
}
if (collision.gameObject.tag == "Gem")
{
Destroy(collision.gameObject);
}
}
private void OnCollisionExit(Collision collision)
{
if (collision.gameObject.tag == "Ground")
{
ground = false;
}
}
}

Unity2d: the player stop moving when I add an animation

I have a problem in unity , the player mouvement is going good until I add an animation the player stop moving even if I press the keyboard keys,when I remove the animator compenent the player move normaly without problems !
I tried separate the animation script from the movement script and still theame problem , I don't think that the problem is comming from the code
playerAnimation code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerAnim : MonoBehaviour
{
Animator anim;
Rigidbody2D rb;
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
anim = gameObject.GetComponent<Animator>();
}
void FixedUpdate()
{
if (rb.velocity.x == 0)
anim.SetBool("isRunning", false);
else
anim.SetBool("isRunning", true);
if (rb.velocity.y > 0)
anim.SetBool("isJumping", true);
else
anim.SetBool("isJumping", false);
}
}
playerMovement script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerControl : MonoBehaviour
{
Rigidbody2D rb;
private float horizontal;
public float runSpeed;
public float jumpPower;
public bool inTheGround;
private SpriteRenderer sp;
Animator anim;
// Start is called before the first frame update
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
sp = gameObject.GetComponent<SpriteRenderer>();
anim = gameObject.GetComponent<Animator>();
}
private void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
}
private void FixedUpdate()
{
rb.velocity = new Vector2(horizontal * runSpeed,
rb.velocity.y);
if (Input.GetButton("Jump")&& inTheGround)
{
rb.velocity = new Vector2(rb.velocity.x,jumpPower);
}
flipping();
Debug.Log(rb.velocity.x);
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("ground"))
inTheGround = true;
}
private void OnCollisionExit2D(Collision2D other)
{
if
(other.gameObject.CompareTag("ground")&&rb.velocity.y>0.1)
inTheGround = false;
}
void flipping()
{
if (Input.GetKey(KeyCode.RightArrow))
sp.flipX = false;
if (Input.GetKey(KeyCode.LeftArrow))
sp.flipX = true;
}
}
Check if Apply Root Motion on Animator Component is set to false. This setting can overwrite your changes of the object's position over time. if not - can you please provide more information, perfectly a screenshot of your player components, and Animator Controller.

System Inputs - How to make my game object jump?

I'm making a simple platformer with a rolling ball that rolls around and collects coins to win each level. I'm using Unity's System input from Unity's package manager to help me with controls and key binding and have successfully gotten my ball to roll around with ease and collect coins with a nice UI setup. However, I would like to implement harder levels where the ball jumps. I can not figure out how to make the ball jump. I know there are others ways to go about this but I just can't figure out how to make it work in the system inputs.
(I know an if statement is needed to test if the ball is grounded however again I'm new and still learning)
Gameplay | OnJump in player input is for jumping | KeyBindings
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using TMPro;
public class PlayerController: MonoBehaviour
{
public float speed = 0;
public bool isGrounded;
public float jumpForce;
public TextMeshProUGUI countText;
public GameObject winTextObject;
private Rigidbody rb;
private int count;
private float movementX;
private float movementY;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
SetCountText();
winTextObject.SetActive(false);
}
private void OnMove(InputValue movementValue)
{
Vector2 movementVector = movementValue.Get<Vector2>();
movementX = movementVector.x;
movementY = movementVector.y;
}
private void onJump(InputValue value)
{
}
void SetCountText()
{
countText.text = "Count: " + count.ToString();
if(count >= 12)
{
winTextObject.SetActive(true);
}
}
private void FixedUpdate()
{
Vector3 movement = new Vector3(movementX, 0.0f, movementY);
rb.AddForce(movement * speed);
}
private void OnTriggerEnter(Collider other)
{
if(other.gameObject.CompareTag("PickUp"))
{
other.gameObject.SetActive(false);
count = count + 1;
SetCountText();
}
}
}
Make sure you create a new tag called Ground and put it on everything you want your player to be able to jump on (the ground).
public float jumpHeight = 5f;
public bool isGrounded;
void Update()
{
if (isGrounded)//Checks if is on ground
{
if (Input.GetButtonDown("Jump"))//If the space is pressed
{
rb.AddForce(Vector3.up * jumpHeight)
}
}
}
void OnCollisionEnter(Collision other)//If touch other object
{
if (other.gameObject.tag == "Ground")//If other object has Ground tag
{
isGrounded = true;
}
}
void OnCollisionExit(Collision other)
{
if (other.gameObject.tag == "Ground")
{
isGrounded = false;
}
}
You can also do if (Input.GetButtonDown("Jump")) as
if (Input.GetKeyDown("space"))
or
if (Input.GetKeyDown(KeyCode.Space))

Unity C# - When having both OnTriggerExit and OnTriggerEnter, only OnTriggerExit gets called

Okay, so I can't see where is my problem. I used OnTriggerEnter for my moving platform. it has rigid body component and the box collider is set to isTrigger on both the platform and player, but for some reason when my platform is triggered by the player, only the OnTriggerExit gets called out . My player is tagged as player in unity... I don't know what to do.
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Moving_Platform : MonoBehaviour
{
[SerializeField]
private float _speed = 1.0f;
[SerializeField]
private Transform _A, _B;
private bool _direction = false;
void FixedUpdate()
{
if(transform.position==_A.position)
{
_direction = false;
}
else if(transform.position== _B.position)
{
_direction = true;
}
if (_direction == false)
{
transform.position = Vector3.MoveTowards(transform.position, _B.position, _speed * Time.deltaTime);
}
if(_direction==true)
{
transform.position = Vector3.MoveTowards(transform.position, _A.position, _speed * Time.deltaTime);
}
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
other.transform.parent = this.transform;
}
}
private void OnTriggerExit(Collider other)
{
Debug.Log("OMFG");
if (other.tag == "Player")
{
Debug.Log("But why!");
other.transform.parent = null;
}
}
}
All Inspectors
It seems that updating to a newer version (2020.x) made the trick.
Thanks for trying.

AddForce doesn't work in Unity

I have the following script
public class SpeedUp : MonoBehaviour {
public Rigidbody2D ball;
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "Ball") {
ball.AddForce(Vector2.left * 1000f);
Debug.Log("ABC");
}
}
}
and every time I run my game, the Debug.Log("ABC") prints ABC in the console, but the Rigidbody doesn't move, it stays as it is. Can someone explain me why, because I don't understand why does the console print work and the Rigidbody doesn't move
This is the code for the Ball
public class Ball : MonoBehaviour {
public Rigidbody2D rb;
public Rigidbody2D hook;
public float releaseTime = 0.15f;
private bool isPressed = false;
void Update()
{
if (isPressed)
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (Vector3.Distance(mousePos, hook.position) > 2.5f)
{
rb.position = hook.position + (mousePos - hook.position).normalized * 2.5f;
}
else
{
rb.position = mousePos;
}
}
}
void OnMouseDown()
{
isPressed = true;
rb.isKinematic = true;
}
void OnMouseUp()
{
isPressed = false;
rb.isKinematic = false;
StartCoroutine(Release());
}
IEnumerator Release()
{
yield return new WaitForSeconds(releaseTime);
GetComponent<SpringJoint2D>().enabled = false;
this.enabled = false;
}
}
The Rigidbody doesn't move may be it's need to getComponenrt()
So, add void Start() method in your the script
public class SpeedUp : MonoBehaviour {
public Rigidbody2D ball;
void Start()
{
ball = ball.GetComponent<Rigidbody2D>();
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "Ball") {
ball.AddForce(Vector2.left * 1000f);
Debug.Log("ABC");
}
}
}

Categories