So I have a sphere for the player, and whenever the player is damaged by an object it should knock the ball into the opposite direction, so I am using AddExplosionForce to do the effect, but sometimes it knocks the player back and sometimes it doesn't do anything. Is there something I can do to fix my code (below) or an alternative to doing this effect? Thank you!
private void OnTriggerEnter(Collider other){
if(other.tag == "Pickup")
{
if(other.GetComponent<pickupScript>().ReturnSize() >= score)
{
score--;
//explodeforce in oposite direction
GetComponent<Rigidbody>().AddExplosionForce(500.0f, other.transform.position, .501f, .5f, ForceMode.Impulse);
//add effects
}
}
Related
I am a starter in Unity and developing a soccer game. I have a problem ,my IF statements conflict each other. Let me explain it in detail.
In order for a ball to stick to player, I have used IF operator, so whenever the distance between the player and the ball is less than < 0.5 , the ball sticks to player and move together with it. Now when I try to set up shooting the ball (I try with "addforce") it doesnt let me, cause the ball is still attached to player and distance is <0.5.
This one is the balls script.
public bool sticktoplayer;
public transform player;
//gameobject Player is attached
float distancetoplayer;
Rigidbody rb;
//balls rigidbody
void Awake ()
{
rb = getComponent<Rigidbody>();
}
void Update()
{
If (!sticktoplayer)
{
float distancetoplayer = Vector3.Distance (player.position, transform.position);
if(distancetoplayer < 0.5f)
{
sticktoplayer = true;
}
}
else
{
transform.position = player.position;
}
if(Input.GetKeyDown(KeyCode.Space))
{
rb.addforce(20, 0, 0, ForceMode.Impulse);
sticktoplayer = false;
}
When the player is not controlling the ball the force is succesfully applied to the ball, but when the ball is attached (distancetoplayer<0.5) then the other IF statements blocks it from shooting.
Maybe there are some work arounds ? Thanks.
I tried to make another if statement.
why dont you try sticking the ball to the player by collision? instead of checking the distance, create a collider with the radius or scale you desire and whenever the ball is inside the collider (when it triggers with the collider) stick it to the player. Because you will not be able to let the ball go since the ball will always be less then 0.5f away from the player once it sticks
have you tried it this way?
if(Input.GetKeyDown(KeyCode.Space))
{
sticktoplayer = false;
rb.addforce(20, 0, 0, ForceMode.Impulse);
}
I am developing a 2d game in unity, and I am trying to add friction to slow the player down when he is on the ground. I launch the player into the air with the rigidbody's add force. I have heard of physics materials, and am currently trying to use them. I am using the 2d version of them, I made one material which had high friction. I add the material to the floor, and then I play the game, and my character is still sliding on the floor. I thought the problem might be with the player not having a physics material, so I added one. It still didn't work.
I tried doing different combinations with the different materials.
I tried attaching a rigidbody, but kinematic to the floor.
I tried looking it up, and couldn't find an answer.
Here is the code that moves the player:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public bool isGrounded = true;
public float fireForce;
Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
camera = camObj.GetComponent<Camera>();
}
void Update()
{
RotateToPoint();
Fire();
}
void OnCollisionEnter2D(Collision2D obj)
{
if (obj.gameObject.tag == "surface")
{
isGrounded = true;
}
}
void OnCollisionExit2D(Collision2D obj)
{
if (obj.gameObject.tag == "surface")
{
isGrounded = false;
}
}
void Fire()
{
if (Input.GetKeyDown(KeyCode.Mouse0) && isGrounded)
{
rb.AddForce(transform.up * fireForce, ForceMode2D.Impulse);
}
}
}
I do not know if I am approaching the problem correctly. If I am not, does anyone know how to avoid slippery game objects. Any help would be appreciated.
Adding a higher angular drag was the solution to my problem. Angular drag is what slows the object down along its rotation. Friction may not always be the problem.
Notice the two highlighted variables. You might want to raise these values (I changed angular drag from its default) to something higher. Adding the physics material might help, you should try this if this first solution doesn't work.
The problem here is that you are not limiting the velocity of the player, so what you can do is set an if statement if the player is touching the floor and the velocity is higher than what you want it to be.
Example:
void FixedUpdate()
{
if (isGrounded == true && rb.velocity.x > 1 || isGrounded == true && rb.velocity.z >1)
{
rb.velocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
}
}
So I'm doing a game where the car automatically moves so whenever the car hits an object it continues floating in the air going forward without begin affected by gravity so that was my main code, I'm still kinda new to this :\
void Update()
{
transform.Translate(Vector3.forward * Speed * Time.deltaTime);
}
then I tried adding this to my code
void Start()
{
coll = GetComponent<Collider>();
coll.isTrigger = true;
}
// Disables gravity on all rigidbodies entering this collider.
void OnTriggerEnter(Collider other)
{
if (other.attachedRigidbody)
other.attachedRigidbody.useGravity = true;
}
but it's still not affected by this whatever I do it just doesn't work an continuously keeps going forward can you help me fix this problem I'm nearly done on that game so if you could help me I'd be very Thankful <3
Note:The car have RigidBody and is affected by gravity and have a huge mass but this doesn't affect any
Also make sure isKinematic is set to false.
void OnTriggerEnter(Collider other)
{
other.attachedRigidbody.useGravity = true;
other.attachedRigidbody.isKinematic = false;
}
void OnCollisionEnter(Collision col)
{
if(col.collider.CompareTag("taghere") || col.collider.name == "Name")
{
// you have to mention the script in which rigidbody you want to disable
}
}
When you add a rigidbody to a gameobject you are effectively handing over direct control of the translation to the rigidbody, and you should no longer alter the transform directly.
The easiest way would be to set the velocity of the plane you want to move in only
void FixedUpdate(){
rigidBody.velocity = new Vector3( speed.x, speed.y,rb.velocity.z);
}
I've joined a game jam, and I'm making a 2D platformer in Unity for it. For this I've created a Jump Pad. Whenever the player character stands on it they'll jump. The problem is that the jump doesn't look like a jump, it looks more like a teleportation upwards. Any fixes? Code below!
void OnTriggerEnter2D(Collider2D other) {
if (other.tag == "Spike") {
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
} else if (other.tag == "Jump Pad") {
rb.AddForce(new Vector2(0f, jumpSpeed));
}
}
Edit
https://imgur.com/a/7MM4QJF
this code worked for me
private void OnCollisionEnter2D(Collision2D other)
{
if(other.gameObject.tag == "player")
{
//you can change 20 to whatever number you want
other.GetComponent<Rigidbody2D>().AddForce(new Vector2(0, 20), ForceMode2D.Impulse);
}
}
Note : be sure to tag the player "player"
Note 2 : be sure is trigger is off
You can try to add upward force like below
rb.AddForce(transform.up*jumpSpeed);
Note: Set a 'realistic' jumpSpeed.
DUDE. lol so i just tried this and what do u know it was giving me trouble, but what i did was take that trigger script off the player and have the jumppad detect the trigger.
if (other.tag == "Player")
{
other.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, jumpSpeed));
}
tag ur player player and put this on the jump pad and set to istrigger
I'm working on my very first Unity game. It's still in prototype and will be very simple anyways, consisting of a cube as the player and spheres as enemies.
I'm trying to write a code with AddForce to knock the player a pretty good distance in an arc in the direction opposite of the enemy when they come in contact, but I still have a primitive understanding of how to use AddForce and can't seem to get force applied in any direction at all. The player just moves through the enemy.
Here's the only thing I could manage to scrap together and it is obviously insufficient:
if (other.gameObject.tag == "Enemy")
{
playerDead = true;
Rigidbody rigidbody = other.GetComponent<Rigidbody> ();
rigidbody.AddForce (transform.forward * 100);
}
I can post a screenshot if it helps.
Instead of transform.forward, use a more tailored direction depending on the position of both units
public float speed = 100;
if (other.gameObject.tag == "Enemy")
{
playerDead = true;
Vector3 direction = (transform.position - other.transform.position).normalized;
other.GetComponent<Rigidbody>().AddForce (direction * speed);
}
Edit: You must make sure that the rigidbody is on the game object calling the OnCollisionEnter function, it cant just be on any of the objects involved in the collision.
I cannot comment so I must make an answer.
You have an isTrigger set up apparenty. Be sure to turn isTrigger OFF or your player will walk through the enemy collider.
[SerializeField]
private float speed = 100;
private bool playerDead;
OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == "Enemy")
{
playerDead = true;
Vector3 direction = (transform.position - collision.transform.position).normalized;
collision.GetComponent<Rigidbody>().AddForce (direction * speed,0,0);
//AddForce is a vector3 apparently and requires (x,y,z)
// Also note that I'm getting errors with the "collision.GetComponent<>"
// You're going to want to remove "collision"
// I think the smarter approach maybe to declare a public Rigidbody variable ( Up Top )
[SerializeField]
private Rigidbody playerRidg;
playerRidg = GetComponent<Rigidbody>().AddForce(direction * speed,0,0);
}
}
My solution using coroutine which toggles a bool "spikes":
Player collision:
private void OnTriggerEnter2D(Collider2D collision){
if (collision.gameObject.tag == "Spike" )
{
StartCoroutine(Knockback());
}
}
Coroutine:
IEnumerator Knockback()
{
spikes = true;
yield return new WaitForSecondsRealtime(0.3f);
spikes = false;
}
Whenever the spikes bool is true player will be moved
void FixedUpdate()
{
if (spikes ==true)
{
Vector2 NewPosition = new Vector2(10.0f, 10.0f);
moveCharacter(NewPosition);
}
}