I have a script attached to a tagged object that pushes my player on trigger. It works perfectly, however my player (after collision) gets dragged back to the tagged object and continues bouncing. How would I stop this. All I want is for my player to get pushed back by the tagged object for a short amount of distance and stay there. Could anyone help me with this?
This is my script:
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Bouncy object")
GetComponent<Rigidbody2D>().AddForce(transform.right * 15, ForceMode2D.Impulse);
}
Try using a vector in your AddForce() method rather than affecting the transform directly:
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Bouncy object")
GetComponent<Rigidbody2D>().AddForce(new Vector2(15, 0), ForceMode2D.Impulse);
}
Related
I have written code to heal the player after colliding with the health potion and then destroy the potion game object making it one time use, however, the gameobject does not get destroyed and the player is not healed. Code is as shown below:
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player" )
{
playerHealthScript.heal();
Destroy(gameObject);
}
}
}
(code below is in a seperate script, used for player health)
public void heal()
{
currentHealth += healingAmount;
currentHealth = Mathf.Clamp(currentHealth, 0, 100);
healthBar.fillAmount = currentHealth / 100f;
}
Before seek for anything, you should Debug.Log("Collision") in your first function, maybe your code is right but the collision isn't detect.
If so, yo could consideer check if the syntax of "Player" is the same as the tag, or maybe your "Player" doesn't have any rigidbody2D ( 2D is important ! ).
I am trying to make a projectile that spawns and when it hits the player he gets destroyed. I have to mention that the projectile would be spawned with the "Instantiate" command making it a "cloned gameobject". In the script I wrote that if the projectile would hit another gameobject with the tag "player" the gameobject it hits would get destroyed but after running the code and the projectile hit the player he didn't get destroyed. I checked and the tag does say "player". I threw in a debug command into the code and managed to find out that the tag doesn't get detected. The script for the projectile spawner and the projectile itself are separate so I'm going to only show the projectile script since it is the problematic script. I have to mention that the script doesn't generate any errors and that the simulation runs fine except for the things I have mentioned above.
public class Bulletboi : MonoBehaviour
{
public float speed;
private Transform player;
private Vector2 target;
public GameObject Elven;
void Start()
{
player = GameObject.FindGameObjectWithTag("player").transform;
target = new Vector2(player.position.x, player.position.y);
}
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
if(transform.position.x == target.x && transform.position.y == target.y)
{
DestroyProjectile();
}
}
void OnEnterTrigger2D(Collision2D other)
{
if (other.gameObject.tag.Equals("player"))
{
Debug.Log("bbbb");
DestroyProjectile();
Destroy(other.gameObject);
}
}
void DestroyProjectile()
{
Destroy(gameObject);
}
}
Never mind I decided to change the script a little bit and I put it on the player and made it detect the tag of the projectile and now it works.
I have a moving platform in a 2D Sidescroller built in Unity 2020.1
The Moving Platform translates between two points using the MoveTo method. It does not have a RigidBody2D component.
I attach the Player to the platform by making it the child of the platform using OnCollisionEnter2D and OnCollisionExit2D to parent the Player to the parent and reset to null respectively. Works great.
I'm using the CharacterController from Standard Assets.
The problem:
The player just walks in place when I try to move him back and forth on the platform.
What I've tried so far:
Changing the current velocity of the player by adding a constant to the x dimension of it's move vector.
Works kinda sorta but that constant needs to be huge to get it to move even a little bit. It's a huge kluge that violates every sense of coding propriety.
Put a RigidBody2D on the platform. Make it kinematic so it doesn't fall to the ground when I land on it. Move the platform via "rb.velocity = new Vector2(speed, rb.velocity.y)";
2a) Attempt to make the Player a child of the kinematic platform.
Player is made a child, but it doesn't move with the platform as expected. I believe that this is because both objects have RigidBody2D components, which I gather don't play well together based on what I've read.
2b) Attempt to add the platform's moving vector to the player's movement vector to make him stay in one place. Player stays stationary to make sure he stays fixed on the platform.
No dice.
I'm all out of ideas. Perusing videos on making player's stick to moving platforms all use the platform to move the player from place to place, without expecting that the game may want the player to move back and forth on the platform as the platform is moving.
I can't believe that this isn't a solved problem, but my Google foo isn't getting me any answers.
Thanks.
I'm a fairly newbie to Unity and C# but I wanted to help so I tried simulating your game for a solution and I didn't run into any problems using this script as the Player movement (you can modify variables as u like, add a separate variable for jump speed to make it smoother etc)
public class Player : MonoBehaviour {
Rigidbody2D rb;
float speed = 7f;
Vector3 movement;
public bool isOnGround;
public bool isOnPlatform;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.position += movement * speed * Time.deltaTime;
Jump();
}
void Jump()
{
if (Input.GetButtonDown("Jump") && isOnGround || Input.GetButtonDown("Jump") && isOnPlatform)
{
rb.AddForce(transform.up * speed, ForceMode2D.Impulse);
}
}
}
Also add an empty child object to your Player gameObject and add a BoxCollider2D at his feet, narrow it down on Y axis like this
also attach this script to that child gameObject to check if player is on the ground(tag ground collider objects with new tag "Ground") so u don't jump infinitely while in the air OR if the player is on the platform(tag platform collider objects with "Platform") so you're still able to jump off it
public class GroundCheck : MonoBehaviour {
Player player;
MovingPlatform mp;
// Start is called before the first frame update
void Start()
{
player = FindObjectOfType<Player>();
mp = FindObjectOfType<MovingPlatform>();
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "Ground")
{
player.isOnGround = true;
}
if (other.gameObject.tag == "Platform")
{
player.isOnPlatform = true;
transform.parent.SetParent(other.transform);
mp.MoveThePlatform();
}
}
private void OnCollisionExit2D(Collision2D other)
{
if (other.gameObject.tag == "Ground")
{
player.isOnGround = false;
}
if (other.gameObject.tag == "Platform")
{
transform.parent.SetParent(null);
}
}
}
and finally for platform movement (no RigidBody2Ds, just a collider)
public class MovingPlatform : MonoBehaviour {
bool moving;
public Transform moveHere;
// Update is called once per frame
void Update()
{
if (moving)
{
gameObject.transform.position = Vector2.MoveTowards(transform.position, moveHere.position, 2f * Time.deltaTime);
}
}
public void MoveThePlatform()
{
moving = true;
}
}
additional images
Player, Platform
P.s. Forgot to add - on Player's RigidBody2D, under Constraints, check the "Freeze Rotation Z" box.
So, I'm making a coin system. When a player collides with trigger collider, i want it to disable only the object it collided with.
this.SetActive(false);
Finding object by name
void OnTriggerEnter (Collider other)
{
if (other.tag == "Coin")
{
this.SetActive(false);
}
}
/
You were very close with your original solution, but you may be misunderstanding what is actually happening here. So I've documented my solution to show the difference.
/* The following script is called when a Rigidbody detects a collider that is
* is set to be a trigger. It then passes that collider as a parameter, to this
* function.
*/
void OnTriggerEnter (Collider other)
{
// So here we have the other / coin collider
// If the gameObject that the collider belongs to has a tag of coin
if (other.gameObject.CompareTag("Coin"))
{
// Set the gameObject that the collider belongs to as SetActive(false)
other.gameObject.SetActive(false);
}
}
If you want the coin to be removed from the scene, because you don't expect it to ever be reactivated, then you can amend this code to the following:
void OnTriggerEnter (Collider other)
{
if (other.gameObject.CompareTag("Coin"))
{
// Removes the coin from your scene instead
Destroy(other.gameObject);
}
}
Right now we work on a Infinity-Runner, and i got this weird bug. After something leaves the Screen it will be catched by a collider that destroys everything. And it works...almost. It will destroy the ground, Background stuff, enemys you jumped over but NOT the newly implemented "roadblocks".
Here is a picture how it looks like, the green placeholder is the roadblock-thingy
http://s4.postimg.org/8uaorv7ot/Bug.png
hope this might help in visualizing what im saying^^.
The Script i use for the Destroyed (the green box collider) is:
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
Debug.Log ("Break is gonna happen");
Debug.Break();
}
else if (other.gameObject.transform.parent)
{
Destroy(other.gameObject.transform.parent.gameObject);
}
else
{
Destroy(other.gameObject);
}
}
and this is the script for the roadblocks:
void OnCollisionEnter2D(Collision2D other)
{
if(other.gameObject.tag == "Player")
{
Debug.Break ();
}
}
so basically nothing that would ever disrupt the DestroyerScript. Its even far more simple than the script on the enemys...but they get destroyed.
Thanks in advance for your help, i can provide more information if need.
(ohh, and all the art in this pic is placeholderstuff^^)
You can try to use OnTriggerExit2D to trigger when your player leave the collider. And makesure you added a suitable collider2d to your sprite before
http://docs.unity3d.com/ScriptReference/Collider2D.OnTriggerExit2D.html
I'm not use it before but I think it might works