Got a problem with my code (on Unity 2D).
I'm trying to make a PacMan like for my class, and my PacMan doesn't want to move at all.
He's animated but he's not moving.
public class PacmanMove : MonoBehaviour {
public float speed = 0.4f;
Vector2 dest = Vector2.zero;
void Start() {
dest = transform.position;
}
void FixedUpdate() {
// Move closer to Destination
Vector2 p = Vector2.MoveTowards(transform.position, dest, speed);
GetComponent<Rigidbody2D>().MovePosition(p);
// Check for Input if not moving
if ((Vector2)transform.position == dest) {
if (Input.GetKey(KeyCode.UpArrow) && valid(Vector2.up))
dest = (Vector2)transform.position + Vector2.up;
if (Input.GetKey(KeyCode.RightArrow) && valid(Vector2.right))
dest = (Vector2)transform.position + Vector2.right;
if (Input.GetKey(KeyCode.DownArrow) && valid(-Vector2.up))
dest = (Vector2)transform.position - Vector2.up;
if (Input.GetKey(KeyCode.LeftArrow) && valid(-Vector2.right))
dest = (Vector2)transform.position - Vector2.right;
}
}
bool valid(Vector2 dir) {
// Cast Line from 'next to Pac-Man' to 'Pac-Man'
Vector2 pos = transform.position;
RaycastHit2D hit = Physics2D.Linecast(pos + dir, pos);
return (hit.collider == GetComponent<Collider2D>());
}
}
Please help me :)
If you don't have to use physics, you can use this.
void FixedUpdate() {
// Check for Input if not moving
if ((Vector2)transform.position == dest) {
if (Input.GetKey(KeyCode.UpArrow) && valid(Vector2.up))
dest = (Vector2)transform.position + Vector2.up;
if (Input.GetKey(KeyCode.RightArrow) && valid(Vector2.right))
dest = (Vector2)transform.position + Vector2.right;
if (Input.GetKey(KeyCode.DownArrow) && valid(-Vector2.up))
dest = (Vector2)transform.position - Vector2.up;
if (Input.GetKey(KeyCode.LeftArrow) && valid(-Vector2.right))
dest = (Vector2)transform.position - Vector2.right;
}
else
{
// Move closer to Destination
transform.position = Vector2.MoveTowards(transform.position, dest, speed);
}
}
Ok, the problem wasn't in the code, it was on my Object's configuration
If you have the same problem, check out if your Object's gravity is on 0 :)
Related
I'm writing some code to create a Minecraft Quake like game but I have an issue with the jump mecanic. When I'm stuck to a wall the player jump to high (see the video).
I use a Rigidbody for the physics and I modify that velocity to move the player. There is a Physic Material on the player's Collider with no consideration for friction or bouncing.
If you have ideas to fix the bug or an alternative to work around the problem, I'm interested.
How it looks like
Here is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum PlayerMovementState {
Sneak,
Walk,
Run
}
public class PlayerControls : MonoBehaviour
{
Rigidbody rb;
Vector3 velocity, desiredVelocity;
PlayerMovementState moveState;
float groundDistance;
[SerializeField]
bool forwardAir, backAir, rightAir, leftAir;
[SerializeField]
LayerMask groundLayer;
[SerializeField]
bool onGround;
bool desiredJump;
float jumpHeight = 1.0f;
private void Awake() {
rb = GetComponent<Rigidbody>();
moveState = PlayerMovementState.Walk;
groundDistance = GetComponentInChildren<Collider>().bounds.extents.y;
}
private void Update() {
Vector2 playerInputs = Vector2.ClampMagnitude(
new Vector2(
Input.GetAxis("Horizontal"),
Input.GetAxis("Vertical")
), 1.0f
);
if (Input.GetKey(KeyCode.LeftShift)) moveState = PlayerMovementState.Sneak;
else if (Input.GetKey(KeyCode.LeftControl)) moveState = PlayerMovementState.Run;
else moveState = PlayerMovementState.Walk;
float speed = moveState == PlayerMovementState.Run ? 10f : (
moveState == PlayerMovementState.Sneak ? 2f : 5f
);
RaycastGround();
onGround = !forwardAir && !backAir && !rightAir && !leftAir;
if (Input.GetButtonDown("Jump")) desiredJump = true;
if (moveState == PlayerMovementState.Sneak)
{
if (forwardAir && playerInputs.y > 0) playerInputs.y = 0f;
if (backAir && playerInputs.y < 0) playerInputs.y = 0f;
if (rightAir && playerInputs.x > 0) playerInputs.x = 0f;
if (leftAir && playerInputs.x < 0) playerInputs.x = 0f;
}
desiredVelocity =
(transform.forward * playerInputs.y + transform.right * playerInputs.x) * speed;
}
private void FixedUpdate() {
velocity = rb.velocity;
float acceleration = 10;
velocity.x = Mathf.MoveTowards(velocity.x, desiredVelocity.x, acceleration);
velocity.z = Mathf.MoveTowards(velocity.z, desiredVelocity.z, acceleration);
if (desiredJump && onGround)
{
desiredJump = false;
float jumpSpeed = Mathf.Sqrt(-2f * Physics.gravity.y * jumpHeight);
velocity.y += jumpSpeed;
}
rb.velocity = velocity;
desiredJump = false;
}
void RaycastGround()
{
forwardAir = !(Physics.Raycast(
transform.position + Vector3.forward * 0.1f,
-Vector3.up,
groundDistance + 0.1f,
groundLayer
));
backAir = !(Physics.Raycast(
transform.position - Vector3.forward * 0.1f,
-Vector3.up,
groundDistance + 0.1f,
groundLayer
));
rightAir = !(Physics.Raycast(
transform.position + Vector3.right * 0.1f,
-Vector3.up,
groundDistance + 0.1f,
groundLayer
));
leftAir = !(Physics.Raycast(
transform.position - Vector3.right * 0.1f,
-Vector3.up,
groundDistance + 0.1f,
groundLayer
));
}
}
Very likely the problem is that the script thinks it's still grounded while it is jumping upwards along the wall.
Depending on what feeling you want, either fix the raycasts such that they only trigger when you are standing directly on top of an object, or you check if the y part of your velocity is <= 0 for your onGround variable.
I did not find a solution to my problem but I found a workaround anyway.
By detecting the walls around the player, I prevent him from moving in the direction of the wall which prevents him from being stuck on it and having this bug when he jumps.
(It means that my problem is not resolved and that I am still looking for a solution)
Video
...
float wallDistance;
...
[SerializeField]
bool forwardWall, backWall, rightWall, leftWall;
...
SpherecastWall();
...
if (forwardWall && playerInputs.y > 0) playerInputs.y = 0f;
if (backWall && playerInputs.y < 0) playerInputs.y = 0f;
if (rightWall && playerInputs.x > 0) playerInputs.x = 0f;
if (leftWall && playerInputs.x < 0) playerInputs.x = 0f;
void SpherecastWall() {
forwardWall = (Physics.SphereCast(
new Ray(transform.position, Vector3.forward),
wallDistance,
.2f,
groundLayer
));
backWall = (Physics.SphereCast(
new Ray(transform.position, -Vector3.forward),
wallDistance,
.2f,
groundLayer
));
rightWall = (Physics.SphereCast(
new Ray(transform.position, Vector3.right),
wallDistance,
.2f,
groundLayer
));
leftWall = (Physics.SphereCast(
new Ray(transform.position, -Vector3.right),
wallDistance,
.2f,
groundLayer
));
}
I think that's because the spheres center gets over the corner of the wall. So when you apply a force the sphere will be pushed over it.
Maybe you could replace the sphere collider of your player with a capsule or a square collider.
I am creating a pacman game using noobtuts' tutorial. https://noobtuts.com/unity/2d-pacman-game However I want to make pacman to be able move on its own. My idea is to make it choose a random direction to move, and it will head into that direction if it is a valid move. How should I do it? Appreciate any answers!
This is noobtuts' code that moves pacman with user input.
Vector2 dest = Vector2.zero;
void Start()
{
dest = transform.position;
disabled = false;
}
void FixedUpdate()
{
// Move closer to Destination
Vector2 p = Vector2.MoveTowards(transform.position, dest, speed);
GetComponent<Rigidbody2D>().MovePosition(p);
// Check for Input if not moving
if ((Vector2)transform.position == dest && !disabled)
{
if (DirectionEmulator.direction == "up" && valid(Vector2.up))
dest = (Vector2)transform.position + Vector2.up;
if (DirectionEmulator.direction == "right" && valid(Vector2.right))
dest = (Vector2)transform.position + Vector2.right;
if (DirectionEmulator.direction == "down" && valid(-Vector2.up))
dest = (Vector2)transform.position - Vector2.up;
if (DirectionEmulator.direction == "left" && valid(-Vector2.right))
dest = (Vector2)transform.position - Vector2.right;
}
// Animation Parameters
Vector2 dir = dest - (Vector2)transform.position;
GetComponent<Animator>().SetFloat("DirX", dir.x);
GetComponent<Animator>().SetFloat("DirY", dir.y);
}
bool valid(Vector2 dir)
{
// Cast Line from 'next to Pac-Man' to 'Pac-Man'
Vector2 pos = transform.position;
RaycastHit2D hit = Physics2D.Linecast(pos + dir, pos);
return (hit.collider == GetComponent<Collider2D>());
}
I managed to make it work as of now, but I believe much more can be improved. Please provide any input if you have any solutions!
private string move;
Vector2 dest = Vector2.zero;
void Start()
{
dest = transform.position;
disabled = false;
move = "right";
}
void FixedUpdate() //use this to decide movement
{
// Move closer to Destination
Vector2 p = Vector2.MoveTowards(transform.position, dest, speed);
GetComponent<Rigidbody2D>().MovePosition(p);
// determine next destination
if ((Vector2)transform.position == dest && !disabled)
{
//check valid direction
if (move == "up" && valid(Vector2.up))
{
dest = (Vector2)transform.position + Vector2.up;
}
if (move == "right" && valid(Vector2.right))
{
dest = (Vector2)transform.position + Vector2.right;
}
if (move == "down" && valid(-Vector2.up))
{
dest = (Vector2)transform.position - Vector2.up;
}
if (move == "left" && valid(-Vector2.right))
{
dest = (Vector2)transform.position - Vector2.right;
}
//if not valid, change direction
// choose random valid direction
System.Random rnd = new System.Random();
int rand = rnd.Next(1, 4);
if (rand == 1 && valid(Vector2.up))
{
move = "up";
}
else if (rand == 2 && valid(Vector2.right))
{
move = "right";
}
else if (rand == 3 && valid(-Vector2.up))
{
move = "down";
}
else if (rand == 4 && valid(-Vector2.right))
{
move = "left";
}
}
// Animation Parameters
Vector2 dir = dest - (Vector2)transform.position;
GetComponent<Animator>().SetFloat("DirX", dir.x);
GetComponent<Animator>().SetFloat("DirY", dir.y);
}
bool valid(Vector2 dir)
{
// Cast Line from 'next to Pac-Man' to 'Pac-Man'
Vector2 pos = transform.position;
RaycastHit2D hit = Physics2D.Linecast(pos + dir, pos);
return (hit.collider == GetComponent<Collider2D>());
}
so I have a script that rotates a cube (by 90 degrees when a direction is pressed) currently im using the oncollision enter to detect walls and when I try to use it to also check if grounded then it will just completely stop everything when i leave one collision and enter another, or it won't fully check when im in mid air and will allow me to move when i don't want to be able to. Any and all help is greatly appreciated.
{
bool isGrounded = true;
private Rigidbody2D rb;
bool leftInput = true;
bool rightInput = true;
public float RollingDuration = 0.2f;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// fixed update is for physics
void FixedUpdate()
{
var dir = Vector3.zero;
if (Input.GetKey(KeyCode.LeftArrow) && leftInput && isGrounded)
{
dir = Vector3.left;
}
if (Input.GetKey(KeyCode.RightArrow) && rightInput && isGrounded)
{
dir = Vector3.right;
}
if (dir !=Vector3.zero && !isRolling)
{
StartCoroutine(Roll(dir));
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
//check to see if our player is grounded
if (collision.gameObject.tag == "Grounded")
{
isGrounded = true;
}
if (collision.gameObject.tag == "LeftWall" || collision.gameObject.tag == "RightWall")
{
StopCoroutine("Roll");
if (collision.gameObject.tag == "LeftWall")
{
leftInput = false;
// we are grounded when touching walls
isGrounded = true;
}
if (collision.gameObject.tag == "RightWall")
{
rightInput = false;
// we are grounded when touching walls
isGrounded = true;
}
if (collision.gameObject.tag == null)
{
isGrounded = false;
}
else
{
isRolling = false;
rb.velocity = Vector2.zero;
rb.velocity = new Vector2(0.0f, 0.0f);
rb.angularVelocity = 0.0f;
rb.transform.rotation = Quaternion.Euler(0.0f, 0.0f, 0.0f);
rb.rotation = 0.0f;
}
}
}
bool isRolling = false;
IEnumerator Roll(Vector3 direction)
{
if (direction == Vector3.right && isGrounded)
{
leftInput = true;
}
else if (direction == Vector3.left && isGrounded)
{
rightInput = true;
}
isRolling = true;
var rotAxis = Vector3.Cross(Vector3.up, direction);
var pivot = (rb.transform.position + Vector3.down * 0.5f) + direction * 0.5f;
var startRotation = rb.transform.rotation;
var endRotation = Quaternion.AngleAxis(90.0f, rotAxis) * startRotation;
var startPosition = rb.transform.position;
var endPosition = rb.transform.position + direction;
var rotSpeed = 90.0f / RollingDuration;
var t = 0.0f;
while (t < RollingDuration && isGrounded)
{
t += Time.deltaTime;
if (t < RollingDuration && isGrounded)
{
rb.transform.RotateAround(pivot, rotAxis, rotSpeed * Time.deltaTime);
yield return null;
}
else
{
rb.transform.rotation = endRotation;
rb.transform.position = endPosition;
}
}
isRolling = false;
}
}
I think the most simple and common way to do ground checks is with casting a ray. So just cast a ray into the direction you want to check or try Overlap functions.
Example:
if(Physics.OverlapCircle(point, radius, layerMask)) {
//do stuff
}
So just cast a ray in all direction you want to check or add a overlap function to each side of the cube.
I'm making a game in unity 2d and when my player goes in to a wall he gets stuck and can't move at all. Here is a video:
VIDEO
I've tried using a composite collider, physics material with friction at 0.
Here is my movement script:
public class PlayerMovement : MonoBehaviour
{
Vector3 pos;
float speed = 2.0f;
private Animator animator;
void Start()
{
pos = transform.position;
animator = gameObject.GetComponent<Animator>();
}
void FixedUpdate()
{
if (Input.GetKey(KeyCode.W) && transform.position == pos)
{ // Up
animator.SetInteger("isWalking", 1);
pos += Vector3.up;
}
if (Input.GetKey(KeyCode.S) && transform.position == pos)
{ // Down
animator.SetInteger("isWalking", 2);
pos += Vector3.down;
}
if (Input.GetKey(KeyCode.D) && transform.position == pos)
{ // Right
animator.SetInteger("isWalking", 3);
pos += Vector3.right;
}
if (Input.GetKey(KeyCode.A) && transform.position == pos)
{ // Left
animator.SetInteger("isWalking", 4);
pos += Vector3.left;
}
if (Input.anyKey == false)
animator.SetInteger("isWalking", 0);
transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime * speed);
}
}
The Player object in your case contains a Rigidbody component. So, it would be better to use some of Rigidbody's movement methods like MovePosition() instead of changing position of GameObject directly via transform.position
Thanks to #Nitro557 i had a new idea instead of basicly teleporting the player around i used a whole different method of moving the player here is the script:
public float runSpeed = 2.0f;
private Rigidbody2D body;
private Animator animator;
private float horizontal;
private float vertical;
private float moveLimiter = 0.7f;
void Start()
{
body = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
}
void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
vertical = Input.GetAxisRaw("Vertical");
if(Input.GetKeyDown(KeyCode.LeftShift))
{
runSpeed += 0.5f;
}
}
private void FixedUpdate()
{
if (horizontal != 0 && vertical != 0)
{
horizontal *= moveLimiter;
vertical *= moveLimiter;
}
body.velocity = new Vector2(horizontal * runSpeed, vertical * runSpeed);
// Up
if (Input.GetKey(KeyCode.W))
animator.SetInteger("isWalking", 1);
// Down
if (Input.GetKey(KeyCode.S))
animator.SetInteger("isWalking", 2);
// Right
if (Input.GetKey(KeyCode.D))
animator.SetInteger("isWalking", 3);
// Left
if (Input.GetKey(KeyCode.A))
animator.SetInteger("isWalking", 4);
if (Input.anyKeyDown == false)
animator.SetInteger("isWalking", 0);
body.velocity = new Vector2(horizontal * runSpeed, vertical * runSpeed);
}
In my game, there are multiple types of projectiles. I have projectiles from the player and also for some enemies. But all these projectiles are directed from the same script.
In order for each projectile to behave differently, I made a prefab for each which instantiates when that "weapon" triggers it. This way each prefab has its own statistics of damage and other components.
Inside the game I want the user to be able to change the prefabs "Damage on hit", but this needs to be reverted back once the user is dead and restarts the game.
So my question is, within my upgrade menu how can I change the value of DamageOnhit for each different projectile since these are all attached to different weapons.
My 3 different projectile prefabs (Going to be more in the future)
The int counter of each prefab
My projectile causes each different projectile to start with standard damage of 1.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//[RequireComponent (typeof(Rigidbody2D))]
public class Projectile : MonoBehaviour {
[Header ("Speed")]
public float baseSpeed;
public float randomSpeed;
public Vector2 SpeedV2;
public Vector2 Direction;
[Header ("Damage")]
public int DamageOnHit = 1;
[Header ("Layers")]
public LayerMask solid_layer;
public LayerMask entities_layer;
[Header ("OnHit FX")]
public GameObject HitFxPrefab;
public GameObject DustFxPrefab;
[Header ("Bounce")]
public bool BounceOnCollide = false;
public int bouncesLeft = 0;
[HideInInspector]
public Health owner; // owner of the projectile
private Vector2 Position; // Current position
private Vector2 movementCounter = Vector2.zero; // Counter for subpixel movement
public BoxCollider2D myCollider;
List<Health> healthsDamaged = new List<Health>(); // List to store healths damaged
void Awake () {
if (myCollider == null) {
myCollider = GetComponent<BoxCollider2D> ();
}
}
void Start () {
// keeping everything Pixel perfect
Position = new Vector2 (Mathf.Round(transform.position.x), Mathf.Round(transform.position.y));
transform.position = Position;
}
void Update () {
SpeedV2 = new Vector2 (transform.right.x, transform.right.y) * (baseSpeed + Random.value * randomSpeed) * Time.deltaTime;
}
void LateUpdate () {
if (SpeedV2.x != 0) {
MoveH (SpeedV2.x);
}
if (SpeedV2.y != 0) {
MoveV (SpeedV2.y);
}
}
void DestroyMe () {
if (HitFxPrefab != null) {
var h = Instantiate (HitFxPrefab, transform.position, transform.rotation);
h.transform.localScale = transform.lossyScale;
h.transform.localRotation = Quaternion.Euler (new Vector3(0f, 0f, Random.value * 360f));
}
Destroy (gameObject);
}
void DestroyMeWall () {
if (HitFxPrefab != null) {
var h = Instantiate (HitFxPrefab, transform.position, transform.rotation);
h.transform.localScale = transform.lossyScale;
h.transform.localRotation = Quaternion.Euler (new Vector3(0f, 0f, Random.value * 360f));
}
Destroy (gameObject);
}
public void BounceHorizontal () {
bouncesLeft--;
transform.right = new Vector3 (-transform.right.x, transform.right.y, transform.right.z);
SpeedV2 *= 0.8f;
}
public void BounceVertical () {
bouncesLeft--;
transform.right = new Vector3 (transform.right.x, -transform.right.y, transform.right.z);
SpeedV2 *= 0.8f;
}
void OnCollideWith (Collider2D col, bool horizontalCol = true) {
var component = col.GetComponent<Health> ();
// If the target the hitbox collided with has a health component and it is not our owner and it is not on the already on the list of healths damaged by the current hitbox
if (component != null && component != owner && !healthsDamaged.Contains(component)) {
// Add the health component to the list of damaged healths
healthsDamaged.Add (component);
// Apply the damage
var didDamage = component.TakeDamage (DamageOnHit);
// Destroy the projectile after applying damage
if (didDamage) {
DestroyMe ();
return;
}
}
// if the projectile hit's a solid object, destroy it
if (col.gameObject.layer == (int)Mathf.Log(solid_layer.value, 2)) {
DestroyMeWall ();
return;
}
}
void OnCollideWithEntity(Collider2D col) {
var component = col.GetComponent<Health> ();
// If the target the hitbox collided with has a health component and it is not our owner and it is not on the already on the list of healths damaged by the current hitbox
if (component != null && component != owner && !healthsDamaged.Contains(component)) {
// Add the health component to the list of damaged healths
healthsDamaged.Add (component);
// Apply the damage
var didDamage = component.TakeDamage (DamageOnHit);
// Destroy the projectile after applying damage
if (didDamage) {
DestroyMe ();
}
}
}
// Function to move the Actor Horizontally, this only stores the float value of the movement to allow for subpixel movement and calls the MoveHExact function to do the actual movement
public bool MoveH(float moveH) {
this.movementCounter.x = this.movementCounter.x + moveH;
int num = (int)Mathf.Round(this.movementCounter.x);
if (num != 0)
{
this.movementCounter.x = this.movementCounter.x - (float)num;
return this.MoveHExact(num);
}
return false;
}
// Function to move the Actor Horizontally, this only stores the float value of the movement to allow for subpixel movement and calls the MoveHExact function to do the actual movement
public bool MoveV(float moveV) {
this.movementCounter.y = this.movementCounter.y + moveV;
int num = (int)Mathf.Round(this.movementCounter.y);
if (num != 0)
{
this.movementCounter.y = this.movementCounter.y - (float)num;
return this.MoveVExact(num);
}
return false;
}
// Function to move the Actor Horizontally an exact integer amount
public bool MoveVExact(int moveV) {
int num = (int)Mathf.Sign((float)moveV);
while (moveV != 0) {
bool solid = CheckColInDir(Vector2.up * (float)num, solid_layer);
if (solid) {
if (BounceOnCollide && bouncesLeft > 0) {
bouncesLeft--;
num = -num;
moveV = -moveV;
BounceVertical ();
} else {
this.movementCounter.x = 0f;
DestroyMeWall ();
return true;
}
}
bool entity = CheckColInDir(Vector2.up * (float)num, entities_layer);
if (entity) {
var entit = CheckColsInDirAll (Vector2.up * (float)num, entities_layer);
OnCollideWithEntity (entit [0]);
}
moveV -= num;
transform.position = new Vector2 (transform.position.x, transform.position.y + (float)num);
}
return false;
}
// Function to move the Actor Horizontally an exact integer amount
public bool MoveHExact(int moveH) {
int num = (int)Mathf.Sign((float)moveH);
while (moveH != 0) {
bool solid = CheckColInDir(Vector2.right * (float)num, solid_layer);
if (solid) {
if (BounceOnCollide && bouncesLeft > 0) {
bouncesLeft--;
num = -num;
moveH = -moveH;
BounceHorizontal ();
} else {
this.movementCounter.x = 0f;
DestroyMeWall ();
return true;
}
}
bool entity = CheckColInDir(Vector2.right * (float)num, entities_layer);
if (entity) {
var entit = CheckColsInDirAll (Vector2.right * (float)num, entities_layer);
OnCollideWithEntity (entit [0]);
}
moveH -= num;
transform.position = new Vector2 (transform.position.x + (float)num, transform.position.y);
}
return false;
}
// Helper function to check if there is any collision within a given layer in a set direction (only use up, down, left, right)
public bool CheckColInDir (Vector2 dir, LayerMask layer) {
Vector2 leftcorner = Vector2.zero;
Vector2 rightcorner = Vector2.zero;
if (dir.x > 0) {
leftcorner = new Vector2 (myCollider.bounds.center.x + myCollider.bounds.extents.x, myCollider.bounds.center.y + myCollider.bounds.extents.y - .1f);
rightcorner = new Vector2 (myCollider.bounds.center.x + myCollider.bounds.extents.x + .5f, myCollider.bounds.center.y - myCollider.bounds.extents.y + .1f);
} else if (dir.x < 0) {
leftcorner = new Vector2 (myCollider.bounds.center.x - myCollider.bounds.extents.x - .5f, myCollider.bounds.center.y + myCollider.bounds.extents.y - .1f);
rightcorner = new Vector2 (myCollider.bounds.center.x - myCollider.bounds.extents.x, myCollider.bounds.center.y - myCollider.bounds.extents.y + .1f);
} else if (dir.y > 0) {
leftcorner = new Vector2 (myCollider.bounds.center.x - myCollider.bounds.extents.x + .1f, myCollider.bounds.center.y + myCollider.bounds.extents.y + .5f);
rightcorner = new Vector2 (myCollider.bounds.center.x + myCollider.bounds.extents.x - .1f, myCollider.bounds.center.y + myCollider.bounds.extents.y);
} else if (dir.y < 0) {
leftcorner = new Vector2 (myCollider.bounds.center.x - myCollider.bounds.extents.x + .1f, myCollider.bounds.center.y - myCollider.bounds.extents.y);
rightcorner = new Vector2 (myCollider.bounds.center.x + myCollider.bounds.extents.x - .1f, myCollider.bounds.center.y - myCollider.bounds.extents.y - .5f);
}
return Physics2D.OverlapArea(leftcorner, rightcorner, layer);
}
// The same as CheckColInDir but it returns a Collider2D array of the colliders you're collisioning with
public Collider2D[] CheckColsInDirAll (Vector2 dir, LayerMask layer) {
Vector2 leftcorner = Vector2.zero;
Vector2 rightcorner = Vector2.zero;
if (dir.x > 0) {
leftcorner = new Vector2 (myCollider.bounds.center.x + myCollider.bounds.extents.x, myCollider.bounds.center.y + myCollider.bounds.extents.y - .1f);
rightcorner = new Vector2 (myCollider.bounds.center.x + myCollider.bounds.extents.x + .5f, myCollider.bounds.center.y - myCollider.bounds.extents.y + .1f);
} else if (dir.x < 0) {
leftcorner = new Vector2 (myCollider.bounds.center.x - myCollider.bounds.extents.x - .5f, myCollider.bounds.center.y + myCollider.bounds.extents.y - .1f);
rightcorner = new Vector2 (myCollider.bounds.center.x - myCollider.bounds.extents.x, myCollider.bounds.center.y - myCollider.bounds.extents.y + .1f);
} else if (dir.y > 0) {
leftcorner = new Vector2 (myCollider.bounds.center.x - myCollider.bounds.extents.x + .1f, myCollider.bounds.center.y + myCollider.bounds.extents.y + .5f);
rightcorner = new Vector2 (myCollider.bounds.center.x + myCollider.bounds.extents.x - .1f, myCollider.bounds.center.y + myCollider.bounds.extents.y);
} else if (dir.y < 0) {
leftcorner = new Vector2 (myCollider.bounds.center.x - myCollider.bounds.extents.x + .1f, myCollider.bounds.center.y - myCollider.bounds.extents.y);
rightcorner = new Vector2 (myCollider.bounds.center.x + myCollider.bounds.extents.x - .1f, myCollider.bounds.center.y - myCollider.bounds.extents.y - .5f);
}
return Physics2D.OverlapAreaAll(leftcorner, rightcorner, layer);
}
}
UpgradeMenu
public void UpgradeDamage ()
{
Projectile.DamageOnHit += 1;
// ScoreManager.Score -= upgradeCost;
UpdateValues();
}
I want to be able to upgrade this value for each different prefab.
I tried this with changing the DamageOnHit to a static, but once I upgrade this value. All the projectiles get upgraded. This is NOT what I want since I want to individually be able to change each prefab.
You create a BulletManager.cs (attach this to an object that will be always active or an empty gameobject)
public static BulletManager instance;
private void Awake
{
if ( instance == null ) //this creates a Singleton so you can access it directly from everywhere, won't go deep into explaining how it works exactly
{
instance = this;
}
else
{
Destroy (gameObject);
}
}
public int machinegunDmg; //set the initial values in the editor
public int shotgunDmg;
public int skeletonDmg;
Now tag all your prefabs with appropriate tags, let's say you use a "MachineGunProj" tag for the machinegun projectile prefab.
The same script you have attached to all prefabs should get the damage from that BulletManager script depending on what prefab you instantiate.
private int DamageOnHit;
//this will get called everytime you instantiate a new prefab that holds this script; it will check for its own tag and depending on it will set the damage in this script to be equal to the appropriate value from BulletManager.cs
private void Start
{
if(this.gameObject.CompareTag("MachineGunProj"))
{
this.DamageOnHit = BulletManager.instance.machinegunDmg;
}
else if(this.gameObject.CompareTag("ShotgunProj"))
{
this.DamageOnHit = BulletManager.instance.shotgunDmg;
}
//else if -- do the same for every prefab you have
}
As for the upgrades, you would need to change the values in BulletManager.cs.
For example:
public void UpgradeMachineGun()
{
BulletManager.instance.machinegunDmg++; //next time you spawn a machinegun prefab it will take the upgraded value
}
*I wrote the code above directly here without the assistance of any text editors or whatever so there is a chance that I have probably missed something but overall this is the idea of how it should work. If something doesn't work I would be more than glad to give you further assistance :)
Two alternatives:
Set DamageOnHit on each instance of the projectile
Each time you Instantiate a new projectile prefab, get its Projectile component and set its DamageOnHit to the desired value.
.
Each time the game restarts, make a copy of each prefab asset
We will call them "ProjectileShotgunProto" and "ProjectileSkeletonProto". You will call Instantiate(ProjectileShotgunProto) them when the player shoots, instead of instantiating your original prefab.
In any case, do not alter the original prefab assets from your code, that will lead to issues.