Hello, I’m currently working on my first 2D project and have 0 programming experience. I really wished that I didn’t have to make this post as the openness of code resource are unlimited and I’m thankful for those people who provided their codes to help me got this far. But I couldn’t seem to find any resource to add a feature to my game.
So, basically I want a shell ejection feature in my game. Which when you press fire it ejects the shell. I wish to have the shell have its own physics. I have added a rigidbody2d on my shell object and written .GetRelativeVector in its script multiplied buy float ejectSpeed. When i Instantiate it, the shell simply ejects downwards without any rotation. I would like it to eject upwards and have a little or random rotation and let gravity do its thing and bring it back down. Also maybe eject on an angle if that is possible.
Please and a huge thanks!
my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShellEjectionCtrl : MonoBehaviour {
public float ejectSpeed;
Rigidbody2D rb;
void Start(){
rb = GetComponent<Rigidbody2D> ();
}
void Update(){
rb.GetRelativeVector (Vector2.up * ejectSpeed);
}
}
Hey I’m new to this too, but I think you might want Velocity.
So:
rb.Velocity instead of rb.GetRelativeVector
Your title says “top down”, but your description is that of a sidescroller.
Basically you need a point to spawn it, and then apply an impulse force in a direction, and rotational force.
The spawn point and direction (if always the same relative to the gun), can be achieved by giving the gun an empty game object as a child, positioned where the shell should appear, and pointing an axis in the direction it should fly.
Give your script a reference to that transform, and use that object’s postion to spawn it.
Once it’s spawned, use that object’s direction to apply a force, and also give it a rotational value.
Here’s an example:
public class Example : MonoBehaviour
{
public GameObject shellPrefab;
public Transform shellOrigin;
public float ejectionForce;
public float ejectionTorque;
public float shellLifetime;
public void Update()
{
if(Input.GetButton("Fire"))
{
// shoot
// eject shell
EjectShell();
}
}
public void EjectShell()
{
// "Quaternion.identity" means default rotation
GameObject newShell = Instantiate(shellPrefab, shellOrigin.position, Quaternion.identity);
Rigidbody2D newShellBody = newShell.GetComponent<Rigidbody2D>();
newShellBody.AddForce(shellOrigin.right * ejectionForce, ForceMode2D.Impulse); // use red axis for direction
newShellBody.AddTorque(ejectionTorque * Random.value, ForceMode2D.Impulse); // randomized torque
Destroy(newShell, shellLifetime);
}
}
It’s cheaper to use a particle system and fire a burst of 1 particle.