Unity: How to create a Knockback vector2 directions script (c#) - c#

I have this topdown game on which I want to create a knockback effect when my player collides with my object. I want to create a knock back script using OnTriggerEnter2D. I want the knock back script to look like this. How Would I do that? (sorry I'm a bit of a noob)
(http://noobtuts.com/content/unity/2d-pong-game/vector2_directions.png)

Hei here is how I got it to work.
First here a basic move script:
public class Move : MonoBehaviour {
public Rigidbody2D rig;
public float speed = 0.2f;
public float maxSpeed = 5f;
void FixedUpdate ()
{
Vector2 vel = new Vector2 ( Input.GetAxis("Horizontal") /5f, Input.GetAxis("Vertical")/5f);
vel.Normalize ();
if (vel.sqrMagnitude > 0f && rig.velocity.sqrMagnitude < maxSpeed) {
rig.AddForce (vel * speed, ForceMode2D.Impulse);
} else {
rig.velocity = Vector2.zero;
}
}
}
And then the bouncing script:
public class CollideCtrl : MonoBehaviour
{
public float speed = 500f;
void OnCollisionEnter2D (Collision2D col) {
if(col.gameObject.CompareTag("Player")){
Debug.Log("Col");
Rigidbody2D rig = col.gameObject.GetComponent<Rigidbody2D>();
if(rig == null) { return;}
Vector2 velocity = rig.velocity;
rig.AddForce( -velocity * speed);
}
}
}
You now need to tweak those values. The effect works but is not perfect to my taste. I invite anyone to improve that answer with their suggestion or own answer coz this is a quick way but not a perfect one. That may give you some lead.
The player needs a Player tag, Rigidbody2D with no gravity and a 2D collision box. The box to collide with needs a BoxCollider2D and isTrigger as false. If you need it as trigger, then change the name and parameter of the collision method.

You could try using physics materials for this, documentation is here:
http://docs.unity3d.com/Manual/class-PhysicMaterial.html
It seems like just what you're looking for!

Related

In unity 2D after applying force to a rigid body how do I make it rotate to face the direction of travel

new to all this. I've tried following a few examples i've found on here but none seem to work. The best I have right now is
rb.transform.up = rb.GetComponent<Rigidbody2D>().velocity.normalized;
but this makes the rigid body rotate immediately to the new direction of travel. is there a way to make it so it rotates slower rather than jumping in one frame to the new direction of travel?
Any help would be appreciated :)
here is the code ive used to apply the force, if that matters? i got it from a tutorial to apply force based on dragging the mouse
public class DragNShoot : MonoBehaviour
{
public float power = 10f;
public Rigidbody2D rb;
public Vector2 minPower;
public Vector2 maxPower;
public TrajectoryLine tl;
Camera cam;
Vector2 force;
Vector3 startPoint;
Vector3 endPoint;
public void Start()
{
cam = Camera.main;
tl = GetComponent<TrajectoryLine>();
}
public void Update()
{
if (Input.GetMouseButtonDown(0))
{
startPoint = cam.ScreenToWorldPoint(Input.mousePosition);
startPoint.z = 15;
}
if (Input.GetMouseButton(0))
{
Vector3 currentPoint = cam.ScreenToWorldPoint(Input.mousePosition);
currentPoint.z = 15;
tl.RenderLine(startPoint, currentPoint);
}
if (Input.GetMouseButtonUp(0))
{
endPoint = cam.ScreenToWorldPoint(Input.mousePosition);
endPoint.z = 15;
force = new Vector2(Mathf.Clamp(startPoint.x - endPoint.x, minPower.x, maxPower.x), Mathf.Clamp(startPoint.y - endPoint.y, minPower.y, maxPower.y));
rb.AddForce(force * power, ForceMode2D.Impulse);
tl.EndLine();
}
}
}
and here is script for the rotation
public class FaceDirectionOfTravel : MonoBehaviour
{
public Rigidbody2D rb;
// Update is called once per frame
void Update()
{
rb.transform.up = rb.GetComponent<Rigidbody2D>().velocity.normalized;
}
}
As you can see, I have just taken the velocity and applied that to the rotation, I guess this just immediatly changes it to match, but I want it to visibly rotate to match the rotation. I have tried some examples I have seen on here for Slerp but that only seemed to leave it in free rotation.. I must be missing something really obvious so thought I would ask on here. Thanks.
EDIT:
So I've kinda worked out a way to get it to work by creating another object on top of the object i wish to rotate and use Slerp to rotate the object on top to slowly rotate to the same as the original object which has to snap immediatly due to force applied the code is simply
public class RotateSprite : MonoBehaviour
{
[SerializeField] private Rigidbody2D rbOfTarget;
[SerializeField] private Rigidbody2D rb;
private void Start()
{
}
// Update is called once per frame
void Update()
{
rb.transform.position = rbOfTarget.transform.position;
rb.transform.rotation = Quaternion.Slerp(rb.transform.rotation, rbOfTarget.transform.rotation, 30* Time.deltaTime);
}
}
if anyone knows a better solution do let me know. Thanks.
Is your game in 3D or 2D? you keep saying it's 2D but the tag says it is 3D and if 2D you wouldn't need a Z position. and if it is in 3D you would have to change the rigidbody2D to just rigidbody.

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.

Projectile not shooting direction of my weapon

So my game is sort of like a 3d top down shooter, so I want my gun to shoot wherever the mouse is and it wont go to the mouse unless im shooting down. If you've seen brackyes game called ball wars, im sort of trying to replicate one like that but the projectile is not shooting the right way.
I got my script from blackthornprods ranged combat tutorial (which is for 2d so maybe thats the issue but I dont know how to solve it) :
public float speed;
public float lifeTime;
private void Start()
{
Invoke("DestoryProjectile", lifeTime);
}
private void Update()
{
transform.Translate(transform.up * speed * Time.deltaTime);
}
void DestroyProjectile()
{
Destroy(gameObject);
}
Appreciate anyone to try!
Here is my other script:
Camera mainCam;
public GameObject projectile;
public Transform shotPoint;
private float timeBtwShots;
public float startTimeBtwShots;
void Awake()
{
mainCam = Camera.main;
}
void Update()
{
float objectDepthFromCamera = Vector3.Dot(
transform.position - mainCam.transform.position,
mainCam.transform.forward);
Vector3 cursorWorldPosition = mainCam.ScreenToWorldPoint(Input.mousePosition
+ Vector3.forward * objectDepthFromCamera);
Vector3 localUpNeeded = Vector3.Cross(Vector3.forward,
cursorWorldPosition - transform.position);
transform.rotation = Quaternion.LookRotation(Vector3.forward, localUpNeeded);
if(timeBtwShots <= 0)
{
if (Input.GetMouseButtonDown(0))
{
Instantiate(projectile, shotPoint.position, transform.rotation);
timeBtwShots = startTimeBtwShots;
}
}
else
{
timeBtwShots -= Time.deltaTime;
}
}
Projectile not shooting direction of my weapon. Simple solution -
First instantiate or pool the instance of projectile.
Set rotation of projection from the rotation of weapon & set location to spawn point
Now fire, or whatever strategy you are using
Consider Global rotation, if you need help, tell me, I will edit and give a snippet of code.
This should work. If doesn't post all necessary code, I will give a better solution.
Here is sample github project I created, just for you. I opened Unity nearly after a year. Please check all the versions.
Must check :
firing in facing direction 💋
just instantiate at spawn point
just added some rotation
I think this should give you concept.
Press X for a rantom rotation
Press Space to shoot a projectile :lol:
The white cube shows that it always shoots at a constant direction

Make an enemy walk around a rectangular platform, like in Metroid

I'm new to Unity, so probably this is a dumb question but I have several days trying to figure it out. I have an enemy walking from one side of a platform to the other. I'm using Raycasting to check if there´s no ground below and turn to the other way.
What I want is for the enemy to walk AROUND the platform (Just like the enemies in Metroid). I set the gravity of the enemy to 0 so it will not fall down, but I don´t know how to make it rotate and keep walking around the platform. I know it could be done with raycasting but I have not clue how to do it.
I will enormously appreciated if anyone can help me with the piece of code I'm missing. Thanks in advance!
public class BlobController : MonoBehaviour {
private Rigidbody2D myRigidBody;
public float moveSpeed;
public LayerMask groundMask;
float myWidth;
// Use this for initialization
void Start ()
{
myRigidBody = GetComponent<Rigidbody2D>();
myWidth = GetComponent<SpriteRenderer> ().bounds.extents.x;
}
// Update is called once per frame
void Update ()
{
}
void FixedUpdate()
{
//Check to see if there's ground in front before moving forward
Vector2 lineCasPos = transform.position - transform.right * myWidth;
Debug.DrawRay (lineCasPos, Vector2.down,Color.red);
bool isGrounded = Physics2D.Raycast (lineCasPos, Vector2.down, 2, groundMask);
//If there's no ground, turn around
if (!isGrounded)
{
Vector3 currRot = transform.eulerAngles;
currRot.y += 180;
transform.eulerAngles = currRot;
}
//Always move forward
Vector2 myVel = myRigidBody.velocity;
myVel.x = -transform.right.x * moveSpeed;
myRigidBody.velocity = myVel;
}
}

How do I make my player with a Rigidbody move with isKinematic checked?

My game is a topdown zombie shooter and whenever the zombies get to the player they bunch up underneath them, to the point where the player can just walk over the zombies. I noticed that when I check isKinematic on the Rigidbody the zombies cant push the player up to go underneath him, so they just run into him(which is what I want). Despite this I am then unable to move. How can i fix this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMoving1 : MonoBehaviour {
public float moveSpeed;
private Rigidbody myRigidbody;
private Vector3 moveInput;
private Vector3 moveVelocity;
private Camera mainCamera;
public GunController theGun;
void Start () {
myRigidbody = GetComponent <Rigidbody>();
mainCamera = FindObjectOfType<Camera>();
}
// Update is called once per frame
void Update () {
moveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
moveVelocity = moveInput * moveSpeed;
Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
float rayLength;
if(groundPlane.Raycast(cameraRay,out rayLength))
{
Vector3 pointToLook = cameraRay.GetPoint(rayLength);
transform.LookAt(new Vector3(pointToLook.x,transform.position.y,pointToLook.z));
}
if (Input.GetMouseButtonDown(0))
theGun.isFiring = true;
if (Input.GetMouseButtonUp(0))
theGun.isFiring = false;
}
void FixedUpdate(){
myRigidbody.velocity = moveVelocity;
}
}
With isKinematic == true You can't change object position through rigidbody, You can only change transform.position.
I think it could be better, if You set isKinematic to false and add stopping distance to enemies, so they can't get too close to player.
Being that your player can no longer be effected by the physics engine, you'd have to manipulate the object's transform manually. Your script isn't ideally setup for it currently, but if I was to hack it into it and try to make it work it would look something like this:
(you can change it from fixedUpdate to update if you're no longer utilizing the physics engine)
void update(){
float x = Input.GetAxisRaw("Horizontal")* Time.Deltatime;
float z = Input.GetAxisRaw("Vertical") * Time.Deltatime;
transform.position = new Vector3(transform.position.x+x,0,transform.position.z+z);
Another way of doing this is to lock the position of Y for the player (assuming Y is the positive "up" direction). isKinimatic is best when you want to move the player or objects around yourself.
I would say upping the mass is better in this case, and you can keep isKinematic unchecked in this case then too. Also apply the lock for Y movement (again if it is the "up" direction from the plane)
Let me know what your solution is regardless, I've had some issues in the past as well with these types of events happening

Categories

Resources