My code doesn't work. When I collide with an object nothings really happening, I made sure that my objects box collider is checked to isTrigger, and I also increase the explosionStrength. What am I doing wrong could anyone help?
public class Knockback : MonoBehaviour
{
public float explosionStrength = 10.0f;
void OnTriggerEnter2D (Collider2D target_)
{
Vector3 forceVec = -target_.GetComponent<Rigidbody2D>().velocity.normalized * explosionStrength;
target_.GetComponent<Rigidbody2D>().AddForce(forceVec,ForceMode2D.Force);
}
}
You are mixing unity3d code and unity 2d code if you are in unity 3d then your code may need to be changed to this...
public class Knockback : MonoBehaviour {
public float explosionStrength = 10.0f;
void OnTriggerEnter (Collider target_){
Vector3 forceVec = -target_.GetComponent<Rigidbody> ().velocity.normalized * explosionStrength;
target_.GetComponent<Rigidbody>().AddForce(forceVec,ForceMode.Force);
}
}
If you are in 2d your code may need to be changed to this
public class Knockback : MonoBehaviour {
public float explosionStrength = 10.0f;
public GameObject player;
void OnTriggerEnter2D (Collider2D target_){
Vector2 forceVec = new Vector2 (-target_.GetComponent<Rigidbody2D> ().velocity.normalized.x * explosionStrength, -target_.GetComponent<Rigidbody2D> ().velocity.normalized.y * explosionStrength);
target_.GetComponent<Rigidbody2D>().AddForce(forceVec,ForceMode2D.Force);
}
}
I have tested the 2d code and it has worked fine. Just make sure you put it on the object to explode not the player.
Related
I have a problem with writing a function that throws spawned ball by pressing a button.
So far, i could only instantiate the ball and it is affected by gravity.
I can not wrap my head arround, how in my code should i add a force to push it with some force. Right now it just plops in front of a player.
I tried to fiddle with .AddForce() on a ball rigidbody2D and still nothing.
I would greatly appreciate if someone could take a look at the code and guide me into some directcion on where to AddForce for ball to make it move?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerControl : MonoBehaviour
{
[Header("Player Atributes")]
[SerializeField] float runSpeed = 10f;
Vector2 moveInput;
Rigidbody2D playerRigidbody2D;
[Header("Ball Settings")]
public bool playerHasABall = false;
[SerializeField] GameObject ball;
[SerializeField] Transform ballSpawn;
void Start()
{
playerRigidbody2D = GetComponent<Rigidbody2D>();
}
void Update()
{
Run();
FlipSprite();
}
void OnMove(InputValue value)
{
moveInput = value.Get<Vector2>();
}
void OnFire(InputValue value)
{
if(!playerHasABall) {return;}
Instantiate(ball, ballSpawn.position, transform.rotation);
playerHasABall = false;
}
void Run()
{
Vector2 playerVelocity = new Vector2 (moveInput.x * runSpeed, playerRigidbody2D.velocity.y);
playerRigidbody2D.velocity = playerVelocity;
}
void FlipSprite()
{
bool playerHasHorizontalSpeed = Mathf.Abs(playerRigidbody2D.velocity.x) > Mathf.Epsilon;
if (playerHasHorizontalSpeed)
{
transform.localScale = new Vector2 (Mathf.Sign(playerRigidbody2D.velocity.x), 1f);
}
}
//Ball picking up script. It destroys the ball with a tag "Ball" and sets a bool playerHasABall to true
private void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Ball")
{
Destroy(other.gameObject);
playerHasABall = true;
}
}
}
So, i manage to fiddle with the .AddForce() method once again and i came up with a solution to my problem.
My OnFire script looks like this:
void OnFire(InputValue value)
{
if(!playerHasABall) {return;}
Instantiate(ball, ballSpawn.position, transform.rotation);
playerHasABall = false;
}
No change here. I made another script called "BallBehaviour.cs" and added it to the ball with a code like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallBehaviour : MonoBehaviour
{
[SerializeField] float ballForce = 20f;
PlayerControl player;
void Start()
{
player = FindObjectOfType<PlayerControl>();
Throw();
}
public void Throw()
{
GetComponent<Rigidbody2D>().AddForce(player.transform.localScale * ballForce, ForceMode2D.Impulse);
}
}
Basically, the method Throw() tells the ball to check the direction the player is facing and then multiply it by ballForce. Then, it uses the ForceMode2d.Impulse method to apply calculated force to the ball for a second and it works on left or right direction.
Thanks Jkimishere for a nudge in a propper direction!
You might need a variable to check if the player is facing right/left.
If the player is, just add force to the ball depending on the direction.
if(!playerHasABall) {return;}
Instantiate(ball,
ballSpawn.position,
transform.rotation);
//Check which way the player is facing and add forrce to that direction.
//Adding a FacingRight boolean might help.....
playerHasABall = false;
This is the error and
I'm using this tutorial
This is my first game in C# and I'm not sure what to do because nobody in the comments said anything about this that I've seen.
This is the exact code that I have wrote.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float movementSpeed;
public Rigidbody2D rb;
public float jumpForce = 20f;
public Transform feet;
public LayerMask groundLayers;
float mx;
private void Update()
{
mx = Input.GetAxisRaw("Horizontal");
if (Input.GetButtonDown("Jump") && IsGrounded())
{
Jump();
}
}
private void FixedUpdate()
{
Vector2 movement = new Vector2(mx * movementSpeed, rb.velocity.y);
rb.velocity = movement;
}
void Jump()
{
Vector2 movement = new Vector2(rb.velocity.x, jumpForce);
rb.velocity = movement;
}
public bool IsGrounded()
{
Collider2D groundCheck = Physics2D.OverlapCircle(feet.position, 0.5f, groundLayers);
if (groundCheck != null)
{
return true;
}
return false;
}
}
Thanks in advance, I'm new to C# and its a big help. :)
For detecting the grounded status of the player i would simply use the OnCollisionEnter() method thet you can implement in your script. It detects when any collider attached to your gameobject touches an other. To tell apart the ground from other objects simply use the following:
if(collision.collider.gameobject.comparetag("ground")
{
//if this is true, set a boolean value to indicate that the player is grounded
//and when the player jumps, always set that boolean to false
}
For this to work you have to set the tag for your floor as "ground" (you have to create that yourself).
To jump, i would rather use rg.AddForce(jumpForce, ForceMode.Impulse) as it's cleaner in my opinion.
Also, as a start i would use Keycode.Space in the GetKeyDown() method instead of "Jump" as it gets rid of a variable that you have to check when debugging.
If it still doesn't work, feel free to write a comment here and let me know.
I am new at game dev, and I have question, I have my enemies prefabs, and enemy script, contains
public Transform player;
So Instead of every time putting my player into that 'slot', I want to make, script will be finding my player, I tried
private Transform player = GameObject.Find("player")
but it shows error
Here is the full script
public class Enemies : MonoBehaviour
{
public Transform player = GameObject.Find("Player");
private Rigidbody2D rb;
private Vector2 movement;
public float speed = 5f;
public int health;
// Start is called before the first frame update
void Start()
{
rb = this.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Vector2 direction = player.position - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
rb.rotation = angle;
direction.Normalize();
movement = direction;
}
private void FixedUpdate()
{
Move(movement);
}
void Move(Vector2 direction)
{
rb.MovePosition((Vector2)transform.position + (direction * speed * Time.deltaTime));
}
private void OnMouseDown()
{
health = health - 1;
if(health <= 0)
{
Destroy(gameObject);
}
}
}
First of all you can't use Find in a static context. (Which is probably the error you are referring to.)
It goes a bit deeper into how c# works but in simple words: The class fields are all initialized even before the constructor is executed and thus at a moment when there still is no instance.
Secondly: GameObject.Find returns a GameObject not a Transform.
So if anything it would probably rather be
// Best would still be to drag this in if possible
[SerializeField] private Transform player;
void Start()
{
if(!player) player = GameObject.Find("Player").transform;
rb = this.GetComponent<Rigidbody2D>();
}
In general I always recommend to not use Find at all if anyhow possible. It is basically just a more expensive way of using some static or manager/provider based code
I'm creating a basic AI script for my enemies in Unity and I have most of it working the way I want it to. The way I have my enemies set up they contain 2 colliders, a polygon collider that destroys the player when touched, and an empty game object that's a child of the enemy that is a circle collider that acts as a trigger. There's a game object that's tagged Straight Road and when the circle collider comes in contact with it, it should run a function called StopMovement(); that sets the enemies movement to 0. I used to Debug.Log(); to check to see if the collider recognizes that it's touching Straight Road and it doesn't. This is my code below. I'm hoping someone has a suggestion.
public class DogAI : GenericController {
public Transform target;
public float chaseRange;
public float maxDistance;
private Vector3 targetDirection;
private float targetDistance;
// Use this for initialization
void Start()
{
base.Start();
}
// Update is called once per frame
void Update()
{
base.Update();
if (target.transform != null)
{
targetDirection = target.transform.position - transform.position;
targetDirection = targetDirection.normalized;
targetDistance = Vector3.Distance(target.position, transform.position);
if (targetDistance <= chaseRange)
{
SetMovement(targetDirection);
}
Vector3 enemyScreenPosition = Camera.main.WorldToScreenPoint(transform.position);
if (targetDistance > maxDistance)
{
Destroy(gameObject);
}
}
}
void StopMovement()
{
SetMovement(new Vector2(0,0));
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Straight Road"))
{
Debug.Log("Stop! There's a road!");//This never shows up in the log?
StopMovement();
}
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Player"))
{
DestroyObject(other.gameObject);
}
}
Generic Controller script below containing the SetMovement() function.
public abstract class GenericController : MonoBehaviour
{
public float movementSpeed = 20;
float animationSpeed = 1;
protected Rigidbody2D rigidbody;
protected Animator animator;
Vector2 movementVector;
float currentSpeed;
protected bool needAnimator = true;
// Use this for initialization
protected void Start()
{
rigidbody = GetComponent<Rigidbody2D>();
if (needAnimator)
{
animator = GetComponent<Animator>();
animator.speed = animationSpeed;
}
}
protected void FixedUpdate()
{
rigidbody.velocity = movementVector;
currentSpeed = rigidbody.velocity.magnitude;
if (needAnimator)
animator.SetFloat("Speed", currentSpeed);
}
public void SetMovement(Vector2 input)
{
movementVector = input * movementSpeed;
}
public void SetMovement(int x, int y)
{
SetMovement(new Vector2(x, y));
}
From the documentation:
MonoBehaviour.OnTriggerEnter2D(Collider2D)
Sent when another object enters a trigger collider attached to this object (2D physics only).
The keyword here is enters. In other words, a trigger is for when something goes inside the area of the collider, like a player entering a region of the map, where the region is a trigger collider. If you want something to happen when a collider collides with the road, i.e. when your CircleCollider comes in contact with the road, then you want the collider to not be a trigger, and you want the functionality to be inside OnCollisionEnter2D.
I'm creating a rocket league like game.
My problem is the ball.
I wrote a scipt who sets up the ball position and rigidbody based on syncvars which the server sets each 0.01 second.
This works well.
The hosting player can touch the ball and it does move on the client aswell.
My code works.
But the problem appears when I'm trying to touch the ball with a client.
The player object glitches into the ball and physics doesn't really work.
The ball gets moved sometimes but it's stil weird movement.
I guess the problem is that the ball doesn't really get the rigidbody changes from the client.
This is my code
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class Ball_Behaviour : NetworkBehaviour {
[SyncVar]
public Vector3 syncedballpos;
public Vector3 ballpos;
[SyncVar]
public Quaternion syncedballrot;
public Quaternion ballrot;
public AudioClip boom;
[SyncVar]
public Vector3 syncedballrigvel;
public Vector3 rigvel;
[SyncVar]
public Quaternion syncedballrigrot;
public Quaternion rigrot;
public GameObject ball;
public Rigidbody rig;
public AudioSource aud;
public GameObject pat;
public float offset;
// Use this for initialization
override
public float GetNetworkSendInterval()
{
return 0.015f;
}
void Start () {
aud = GetComponent<AudioSource>();
GetNetworkSendInterval();
ball = this.gameObject;
rig = GetComponent<Rigidbody>();
offset = 1;
}
// Update is called once per frame
void Update ()
{
if (isServer)
{
setball();
}
if (Vector3.Distance(rigvel, syncedballrigvel) > offset)
{
rig.velocity=Vector3.Lerp(rigvel, syncedballrigvel, 1f)*Time.deltaTime*0.05f;
}
else
{
if (Vector3.Distance(ballpos, syncedballpos) > offset)
{
this.transform.position = Vector3.Lerp(ballpos, syncedballpos, 1f) * Time.deltaTime * 0.05f;
}
/* if (Quaternion.Angle(rigrot,syncedballrigrot)>1f)
{
rig.rotation = Quaternion.Slerp(rigrot,syncedballrigrot,0.7f);
}
if (Quaternion.Angle(ballrot, syncedballrot) > 1f)
{
this.transform.rotation = Quaternion.Slerp(ballrot, syncedballrot, 0.7f);
}
*/
}
}
[ServerCallback]
void setball()
{
syncedballrigvel = rig.velocity;
syncedballrigrot = rig.rotation;
syncedballpos = this.transform.position;
syncedballrot = this.transform.rotation;
// RpcDoOnClient(syncedballpos);
}
void OnCollisionEnter(Collision col)
{
aud.Play();
}
public void scored()
{
this.GetComponent<MeshRenderer>().enabled = false;
Instantiate(pat, this.transform.position, this.transform.rotation);
aud.PlayOneShot(boom,2);
}
}