Can't get my collision to work (platformer) XNA - c#

I'm learning XNA right now and i'm pretty new to programming in general. I'm making a platformer now but when I walk into a platform from left or right I get teleported to the top of the platform. The collision is only working with the last platform added to the platform list.
This is in Game class:
LoadContent:
for (int i = 0; i < 3; i++)
{
platform0List.Add(new Platform0(new Vector2(70 + (i * 300), 400), platform0Texture));
}
Update:
protected override void Update(GameTime gameTime)
{
keyboard = Keyboard.GetState();
player.Update(keyboard, keyboardPrev, platform0List);
foreach (Platform0 platform in platform0List)
{
if (!Move_Free(player.position.X, player.position.Y + player.gravity, player.texture.Width, player.texture.Height, platform.rectangle) && player.gravity >= 0)
{
player.ground = true;
if (player.position.Y + player.texture.Height + player.gravity > platform.position.Y)
{
player.position.Y = platform.position.Y - player.texture.Height;
}
else if (player.position.Y + player.texture.Height + player.gravity < platform.position.Y)
{
player.gravity = platform.position.Y - player.texture.Height;
}
break;
}
else
{
player.ground = false;
}
}
if (keyboard.IsKeyDown(Keys.Escape)) this.Exit();
keyboardPrev = keyboard;
base.Update(gameTime);
}
This is my Move_Free method
public static bool Move_Free(float x, float y, int width, int height, Rectangle rectangle)
{
Rectangle rect = new Rectangle((int)x,(int)y,width,height);
if(rect.Intersects(rectangle))
{
return false;
}
else
{
return true;
}
}
This is in Player class
foreach (Platform0 platform in platform0List)
{
if (keyboard.IsKeyDown(Keys.Right) && Game1.Move_Free(position.X + 5, position.Y, texture.Width, texture.Height, platform.rectangle))
{
moveRight = true;
}
else if (keyboard.IsKeyDown(Keys.Right) && ((position.X + texture.Width - platform.position.X) * -1) > 0)
{
position.X += (position.X + texture.Width - platform.position.X) * -1;
}
else
{
moveRight = false;
}
if (keyboard.IsKeyDown(Keys.Left) && Game1.Move_Free(position.X - 5, position.Y, texture.Width, texture.Height, platform.rectangle))
{
moveLeft = true;
}
else if (keyboard.IsKeyDown(Keys.Left) && position.X - (platform.position.X + platform.texture.Width) > 0)
{
position.X -= position.X - (platform.position.X + platform.texture.Width);
}
else
{
moveLeft = false;
}
}
if (moveRight) position.X += 5;
if (moveLeft) position.X -= 5;
if (keyboard.IsKeyDown(Keys.Up) && ground)
{
gravity = -10;
ground = false;
}
if(ground)
{
gravity = 0;
}
else
{
gravity += 9.8f / 60f;
position.Y += gravity;
}

Each iteration of your forloop overwrites your moveLeft and moveRight variables.
Therefore, only the last platform values will remain.

Related

How to find which collider with same tag is touching my character firstly when multiple colliders are touching my character same time

I'm trying to figure out which collider with same tag is touching my character firstly when multiple colliders are touching my character same time.
if (col.transform.gameObject.tag == "enemy") {
hit = true;
rgd.AddForce(new Vector2(0, 2.150f), ForceMode2D.Impulse);
if (transform.position.x-col.transform.gameObject.transform.position.x < 0)
{
rgd.AddForce(-1*rgd.transform.right * 40);
}
else
{
rgd.AddForce(1*rgd.transform.right * 40);
}
if (Mathf.Approximately (angle, 0)) {
Destroy (col.transform.gameObject);
damage = 0;
} else {
damage = 25;
}
enemydamageSound.Play();
}
I solved it by adding a few code.Here is my new code:
private int jumpCount = 0;
if (col.transform.gameObject.tag == "ground")
{
isGround = true;
jumpped = true;
jumpCount = 0;
}
if (col.transform.gameObject.tag == "enemy")
{
hit = true;
if (!isGround && jumpCount == 0)
{
rgd.AddForce(new Vector2(0, 2.150f), ForceMode2D.Impulse);
jumpCount++;
}
if (transform.position.x - col.transform.gameObject.transform.position.x < 0)
{
if (jumpCount == 0)
{
rgd.AddForce(new Vector2(0, 2f), ForceMode2D.Impulse);
}
rgd.AddForce(-1 * rgd.transform.right * 40);
}
else
{
if (jumpCount == 0)
{
rgd.AddForce(new Vector2(0, 2f), ForceMode2D.Impulse);
}
rgd.AddForce(1 * rgd.transform.right * 40);
}
if (Mathf.Approximately(angle, 0))
{
Destroy(col.transform.gameObject);
damage = 0;
}
else
{
damage = 25;
}
enemydamageSound.Play();
}

PONG Collision Need assistance

I have to make pong for a school assignment. Everything was going pretty well
until I came to the collision part. Can somebody maybe help me?
I am doing it in visual studios c#, and I am a beginner, so I don't understand a lot. I have tried a lot of different solutions, but none of them seems to have worked out.
public override void GameStart()
{
}
public override void GameEnd()
{
}
public override void Update()
{
float DeltaTime = GAME_ENGINE.GetDeltaTime();
//Frame Rate Unlock
if (GAME_ENGINE.GetKeyDown(Key.V))
{
bool isLocked = GAME_ENGINE.GetVSync();
GAME_ENGINE.SetVSync(!isLocked);
}
//Player 1 Movement
if (GAME_ENGINE.GetKey(Key.W) && m_PlayerY1 != 0)
{
m_PlayerY1 -= 250 * DeltaTime;
}
if (GAME_ENGINE.GetKey(Key.S) && m_PlayerY1 != 300)
{
m_PlayerY1 += 250 * DeltaTime;
}
if (m_PlayerY1 < 0)
{
m_PlayerY1 = 0;
}
if (m_PlayerY1 > 350)
{
m_PlayerY1 = 350;
}
//Player 2
if (GAME_ENGINE.GetKey(Key.Up) && m_PlayerY2 != 0)
{
m_PlayerY2 -= 250 * DeltaTime;
}
if (GAME_ENGINE.GetKey(Key.Down) && m_PlayerY2 != 300)
{
m_PlayerY2 += 250 * DeltaTime;
}
if (m_PlayerY2 < 0)
{
m_PlayerY2 = 0;
}
if (m_PlayerY2 > 350)
{
m_PlayerY2 = 350;
}
//Ball Stuff
Random RnD = new Random();
m_XBallSpeed = RnD.Next(2, 3);
m_YBallSpeed = RnD.Next(2, 3);
m_XBall += m_XBallSpeed;
if (m_XBall < 0)
{
m_XBallSpeed = -m_XBallSpeed;
}
else if (m_XBall + m_BallWidth > GAME_ENGINE.GetScreenWidth())
{
m_XBallSpeed = -m_XBallSpeed;
}
m_YBall += m_YBallSpeed;
if (m_YBall < 0)
{
m_YBallSpeed = -m_YBallSpeed;
}
else if (m_YBall + m_BallHeight > GAME_ENGINE.GetScreenHeight())
{
m_YBallSpeed = -m_YBallSpeed;
}
if (m_XBall >= m_PlayerHeight1 && m_YBall >= m_PlayerHeight2)
{
m_XBallSpeed += 1;
m_YBallSpeed += 1;
m_XBallSpeed = -m_YBallSpeed;
}
if (m_YBall >= m_PlayerWidth1 && m_YBall >= m_PlayerWidth2)
{
m_XBallSpeed += 1;
m_YBallSpeed += 1;
m_XBallSpeed = -m_YBallSpeed;
}
}
public override void Paint()
{
//Player 1 and 2 and Ball
GAME_ENGINE.SetColor(255, 255, 255);
GAME_ENGINE.FillRectangle(m_PlayerX1, m_PlayerY1, m_PlayerWidth1, m_PlayerHeight1);
GAME_ENGINE.FillRectangle(m_PlayerX2, m_PlayerY2, m_PlayerWidth2, m_PlayerHeight2);
GAME_ENGINE.FillRoundedRectangle(m_XBall, m_YBall, m_BallWidth, m_BallHeight, 50, 50);
}

Cannot call or set a variable from another script in C#

EDIT Full Scripts:
SoldierController Script (removed few variables due to character limitaton). I have declared 1 new variable called DontMove and want this to be called from the ElevatorOpen script. Issue I am having is calling this script even though this is set to static and public.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
public class SoldierController : MonoBehaviour
{
#region Variables
public Transform gunPoint;
public GameObject bulletPrefab;
//Components
protected Animator animator;
private GameObject camera;
private Camera cam;
public GameObject splashFX;
public AudioClip gunShotSound;
//action variables
public static bool dontMove = false;
public float walkSpeed = 1.35f;
bool canwalk = true;
float moveSpeed;
public float runSpeed = 1f;
public float rotationSpeed = 20f;
bool isMoving = false;
public bool walking = true;
bool areWalking;
Vector3 newVelocity;
Vector3 inputVec;
//aiming/shooting variables
bool canAim;
bool canFire = true;
public bool aiming = true;
bool isAiming = false;
public bool grenading = true;
bool isGrenading;
bool canGrenade = true;
int weaponType = 0;
//Weapon Prefabs
GameObject pistol;
GameObject rifle;
GameObject launcher;
GameObject heavy;
#endregion
#region Initialization
void Start()
{
canMove = true;
//dontMove = false;
//set the animator component
animator = GetComponentInChildren<Animator>();
//sets the weight on any additional layers to 1
if (animator.layerCount >= 2)
{
animator.SetLayerWeight(1, 1);
}
//Get the camera
camera = GameObject.FindGameObjectWithTag("MainCamera");
cam = camera.GetComponent<Camera>();
//sets the Weapon to 1 in the animator
weaponType = 1;
StartCoroutine(COSwitchWeapon("Weapon", 1));
}
#endregion
#region Update
void Update()
{
x = Input.GetAxisRaw("Horizontal");
//z = Input.GetAxisRaw("Vertical");
inputVec = new Vector3(x, 0, z);
if (animator)
{
CoverUpdate();
JumpingUpdate();
if (!isSwimming) //character can't do any actions while swimming
{
if (Input.GetKeyDown(KeyCode.LeftControl) && canFire && cover != 1 && covering)
{
Fire();
}
if (Input.GetMouseButtonDown(0) && canFire && cover != 1 && covering)
{
Fire();
}
if (Input.GetButton("Fire2") && canAim && aiming)
{
isAiming = true;
}
else
{
isAiming = false;
}
}
}
}
#endregion
#region Fixed/Late Updates
void FixedUpdate()
{
CheckForGrounded();
if (!isSwimming) //character is not swimming
{
//gravity
GetComponent<Rigidbody>().AddForce(0, gravity, 0, ForceMode.Acceleration);
if (aircontrol)
AirControl();
//check if we aren't in cover and can move
if (!covered && canMove)
{
if (canPushPull)
{
if (!isPushPulling)
moveSpeed = UpdateMovement(); //if we are not pushpull use normal movement speed
else
moveSpeed = PushPull(); //we are push pulling, use pushpullspeed
}
else
moveSpeed = UpdateMovement();
}
}
else //character is swimming
{
moveSpeed = Swimming();
}
}
void LateUpdate()
{
//Get local velocity of charcter
float velocityXel = transform.InverseTransformDirection(GetComponent<Rigidbody>().velocity).x;
float velocityZel = transform.InverseTransformDirection(GetComponent<Rigidbody>().velocity).z;
//Update animator with movement values
animator.SetFloat("Velocity X", velocityXel / runSpeed);
animator.SetFloat("Velocity Z", velocityZel / runSpeed);
//if we are moving, set our animator
if (moveSpeed > 0)
{
isMoving = true;
animator.SetBool("Moving", true);
}
else
{
isMoving = false;
animator.SetBool("Moving", false);
}
}
#endregion
void RotateTowardsMovementDir()
{
// Rotation
if (inputVec != Vector3.zero && !isAiming)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(inputVec), Time.deltaTime * rotationSpeed);
}
}
#region UpdateMovement
float UpdateMovement()
{
Vector3 motion = inputVec;
if (isGrounded)
{
//reduce input for diagonal movement
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//apply velocity based on platform speed to prevent sliding
float platformVelocity = platformSpeed.magnitude * .4f;
Vector3 platformAdjust = platformSpeed * platformVelocity;
//set speed by walking / running
if (areWalking)
{
canAim = false;
//check if we are on a platform and if its animated, apply the platform's velocity
if (!platformAnimated)
{
newVelocity = motion * walkSpeed + platformAdjust;
}
else
{
newVelocity = motion * walkSpeed + platformAdjust;
}
}
else
{
//check if we are on a platform and if its animated, apply the platform's velocity
if (!platformAnimated)
{
newVelocity = motion * runSpeed + platformAdjust;
}
else
{
newVelocity = motion * runSpeed + platformSpeed;
}
}
}
else
{
//if we are falling use momentum
newVelocity = GetComponent<Rigidbody>().velocity;
}
// limit velocity to x and z, by maintaining current y velocity:
newVelocity.y = GetComponent<Rigidbody>().velocity.y;
GetComponent<Rigidbody>().velocity = newVelocity;
if (!isAiming)
RotateTowardsMovementDir();
//if the right mouse button is held look at the mouse cursor
if (isAiming)
{
//make character point at mouse
Quaternion targetRotation;
float rotationSpeed = 40f;
Vector3 mousePos = Input.mousePosition;
mousePos = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.transform.position.y - transform.position.y));
targetRotation = Quaternion.LookRotation(mousePos - new Vector3(transform.position.x, 0, transform.position.z));
transform.eulerAngles = Vector3.up * Mathf.MoveTowardsAngle(transform.eulerAngles.y, targetRotation.eulerAngles.y, (rotationSpeed * Time.deltaTime) * rotationSpeed);
}
//calculate the rolling time
rollduration -= rolldamp;
if (rollduration > 0)
{
isRolling = true;
}
else
{
isRolling = false;
}
if (isRolling)
{
Vector3 localforward = transform.TransformDirection(0, 0, 1);
GetComponent<Rigidbody>().velocity = localforward * rollSpeed;
}
//return a movement value for the animator
return inputVec.magnitude;
}
#endregion
#region AirControl
void AirControl()
{
float x = Input.GetAxisRaw("Horizontal");
float z = Input.GetAxisRaw("Vertical");
Vector3 inputVec = new Vector3(x, 0, z);
Vector3 motion = inputVec;
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//allow some control the air
GetComponent<Rigidbody>().AddForce(motion * inAirSpeed, ForceMode.Acceleration);
//limit the amount of velocity we can achieve
float velocityX = 0;
float velocityZ = 0;
if (GetComponent<Rigidbody>().velocity.x > maxVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - maxVelocity;
if (velocityX < 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.x < minVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - minVelocity;
if (velocityX > 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z > maxVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - maxVelocity;
if (velocityZ < 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z < minVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - minVelocity;
if (velocityZ > 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
}
#endregion
#region Swimming
float Swimming()
{
Vector3 motion = inputVec;
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//movement is using swimSpeed
GetComponent<Rigidbody>().AddForce(motion * swimSpeed, ForceMode.Acceleration);
//limit the amount of velocity we can achieve
float velocityX = 0;
float velocityZ = 0;
if (GetComponent<Rigidbody>().velocity.x > maxVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - maxVelocity;
if (velocityX < 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.x < minVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - minVelocity;
if (velocityX > 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z > maxVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - maxVelocity;
if (velocityZ < 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z < minVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - minVelocity;
if (velocityZ > 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
RotateTowardsMovementDir();
//return a movement value for the animator
return inputVec.magnitude;
}
#endregion
#region PushPull
float PushPull()
{
//set bools
canAim = false;
canAbility = false;
canCover = false;
canFire = false;
canGrenade = false;
canItem = false;
canJump = false;
canMelee = false;
canReload = false;
canRoll = false;
canSignal = false;
canwalk = false;
isPushPulling = true;
animator.SetBool("PushPull", true);
Vector3 motion = inputVec;
//reduce input for diagonal movement
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//movement is using pushpull speed
GetComponent<Rigidbody>().velocity = motion * pushPullSpeed;
//return a movement value for the animator
return inputVec.magnitude;
}
#endregion
#region Grounding
void CheckForGrounded()
{
float distanceToGround;
float threshold = .45f;
RaycastHit hit;
Vector3 offset = new Vector3(0, .4f, 0);
if (Physics.Raycast((transform.position + offset), -Vector3.up, out hit, 100f))
{
distanceToGround = hit.distance;
if (distanceToGround < threshold)
{
isGrounded = true;
//moving platforms
if (hit.transform.tag == "Platform")
{
//get platform script from collided platform
Platform platformScript = hit.transform.GetComponent<Platform>();
//check if the platform is moved with physics or if it is animated and get velocity from it
if (platformScript.animated)
{
platformSpeed = platformScript.velocity;
platformAnimated = true;
}
if (!platformScript.animated)
{
platformSpeed = hit.transform.GetComponent<Rigidbody>().velocity;
}
//get the platform rotation to pass into our character when they are on a platform
platformFacing = hit.transform.rotation;
}
else
{
//if we are not on a platform, reset platform variables
platformSpeed = new Vector3(0, 0, 0);
platformFacing.eulerAngles = new Vector3(0, 0, 0);
Platform platformScript = null;
float platformVelocity = 0f;
}
}
else
{
isGrounded = false;
}
}
}
#endregion
#region Cover
void CoverUpdate()
{
/*
if (covering && !isSwimming)
{
//check if we press cover button
if (Input.GetButtonDown("Cover") && canCover && !covered)
{
//set variables
animator.SetBool("Moving", false);
Input.ResetInputAxes();
isMoving = false;
animator.SetBool("Moving", false);
covered = true;
canReload = true;
canCover = false;
canItem = false;
canMelee = false;
canFire = false;
canItem = false;
canGrenade = false;
canJump = false;
cover = 1;
animator.SetInteger("Cover", 1);
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
}
else
{
//if we are already in cover and press the cover button, get out of cover
if (Input.GetButtonDown("Cover") && covered == true)
{
//set the animation back to idle
animator.SetInteger("Cover", 3);
//set variables
cover = 0;
covered = false;
canCover = true;
canAbility = true;
canAim = true;
canItem = true;
canGrenade = true;
canFire = true;
}
}
}*/
}
#endregion
#region Jumping
void JumpingUpdate()
{
if (!isSwimming) //if character is not swimming
{
//If the character is on the ground
if (isGrounded)
{
//set the animation back to idle
animator.SetInteger("Jumping", 0);
//set variables
jumped = false;
//check if we press jump button
if (canJump && Input.GetButtonDown("Jump") && cover != 1)
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity += jumpSpeed * Vector3.up;
//set variables
animator.SetTrigger("Jump");
animator.SetInteger("Jumping", 2);
}
}
else
{
//set bools
canDoubleJump = true;
if (!falling && !jumped)
{
//set the animation back to idle
animator.SetInteger("Jumping", 2);
falling = true;
}
//if double jumping is allowed and jump is pressed, do a double jump
if (canDoubleJump && doublejumping && Input.GetButtonDown("Jump") && doublejumped != true && doublejumping)
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity += doublejumpSpeed * Vector3.up;
//set the animation to double jump
animator.SetInteger("Jumping", 3);
//set variables
canJump = false;
doublejumped = true;
isJumping = true;
falling = false;
jumped = false;
}
}
}
else //characer is swimming
{
//check if we press jump button
if (canSwim && Input.GetButtonDown("Jump"))
{
if (x != 0 || z != 0) //if the character movement input is not 0, swim in facing direction
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity += swimBurstSpeed * transform.forward;
animator.SetTrigger("SwimBurst");
}
else //we are not trying to move the character, jump up
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity = jumpSpeed * Vector3.up;
//set variables
animator.SetTrigger("Jump");
canJump = false;
isJumping = true;
canDoubleJump = true;
jumped = true;
animator.SetInteger("Jumping", 2);
}
}
}
}
#endregion
#region Misc Methods
void Rolling()
{
StartCoroutine(COPlayOneShot("Rolling"));
covered = false;
canCover = false;
cover = 0;
animator.SetInteger("Cover", 0);
isRolling = true;
}
void Fire()
{
StartCoroutine(COPlayOneShot("Fire"));
(Instantiate(bulletPrefab, gunPoint.position, transform.root.rotation) as GameObject).GetComponent<BulletController>().damage = 20;
StartCoroutine(WeaponCooldown());
GetComponent<AudioSource>().PlayOneShot(gunShotSound);
}
IEnumerator WeaponCooldown()
{
canFire = false;
yield return new WaitForSeconds(0.1f);
canFire = true;
}
void Ability()
{
StartCoroutine(COPlayOneShot("Ability"));
}
void Item()
{
StartCoroutine(COPlayOneShot("Item"));
}
void Grenade()
{
StartCoroutine(COGrenade());
isGrenading = true;
}
void Reload()
{
StartCoroutine(COReload(weaponType));
isReloading = true;
}
void Signal()
{
StartCoroutine(COPlayOneShot("Signal"));
}
void Melee()
{
StartCoroutine(COMelee());
isMelee = true;
}
void Pain()
{
StartCoroutine(COPlayOneShot("Pain"));
}
//plays a random death# animation between 1-3
void Death()
{
//stop character movement
animator.SetBool("Moving", true);
Input.ResetInputAxes();
isMoving = false;
int deathnumber = 5;
animator.SetInteger("Death", deathnumber);
}
#endregion
#region CORoutines
//function to play a one shot animation
public IEnumerator COPlayOneShot(string paramName)
{
animator.SetBool(paramName, true);
yield return null;
animator.SetBool(paramName, false);
}
//function to switch weapons
public IEnumerator COSwitchWeapon(string weaponname, int weaponnumber)
{
//sets Weapon to 0 first to reset
animator.SetInteger(weaponname, 0);
yield return null;
yield return null;
animator.SetInteger(weaponname, weaponnumber);
}
//function to reload
public IEnumerator COReload(int weapon)
{
//sets Weapon to 0 first to reset
animator.SetBool("Reload", true);
yield return null;
animator.SetBool("Reload", false);
float wait = 0;
if (weaponType == 1 || weaponType == 2)
{
wait = 1.85f;
}
if (weaponType == 3 || weaponType == 4)
{
wait = 3f;
}
yield return new WaitForSeconds(wait);
isReloading = false;
}
//function to grenade
IEnumerator COGrenade()
{
//sets Weapon to 0 first to reset
animator.SetBool("Grenade", true);
yield return null;
animator.SetBool("Grenade", false);
yield return new WaitForSeconds(1);
isGrenading = false;
}
//function to Melee
IEnumerator COMelee()
{
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
canMove = false;
isMoving = false;
animator.SetTrigger("Melee");
yield return new WaitForSeconds(.7f);
isMelee = false;
canMove = true;
}
IEnumerator COKnockback()
{
StartCoroutine(COPlayOneShot("Knockback"));
return null;
}
public IEnumerator CODazed()
{
StartCoroutine(COPlayOneShot("Dazed"));
Debug.Log("Cant Move");
canMove = false;
canFire = false;
canAim = false;
canJump = false;
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
yield return new WaitForSeconds(3.0f);
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
canMove = true;
canFire = true;
canAim = true;
canJump = true;
}
#endregion
#region WeaponSwitching
void WeaponSwitch()
{
weaponType++;
if (weaponType == 1)
{
//enables pistol, disables other weapons
pistol.SetActive(true);
rifle.SetActive(false);
launcher.SetActive(false);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 1));
}
if (weaponType == 2)
{
//enables rifle, disables other weapons
pistol.SetActive(false);
rifle.SetActive(true);
launcher.SetActive(false);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 2));
}
if (weaponType == 3)
{
//enables launcher, disables other weapons
pistol.SetActive(false);
rifle.SetActive(false);
launcher.SetActive(true);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 3));
}
if (weaponType == 4)
{
//enables heavy, disables other weapons
pistol.SetActive(false);
rifle.SetActive(false);
launcher.SetActive(false);
heavy.SetActive(true);
StartCoroutine(COSwitchWeapon("Weapon", 4));
}
if (weaponType == 5)
{
//enables pistol, disables other weapons
pistol.SetActive(true);
rifle.SetActive(false);
launcher.SetActive(false);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 1));
weaponType = 1;
}
}
#endregion
}
And finally the elevatorOPen script:
using UnityEngine;
using System.Collections;
public class ElevatorOpen : MonoBehaviour
{
private Animator animator;
public AudioClip ElevatorBing;
void Awake ()
{
animator = GetComponent <Animator>();
}
void OnTriggerEnter (Collider other)
{
if (other.gameObject.tag == "Player") {
animator.SetInteger ("Open", 1);
GetComponent<AudioSource>().PlayOneShot(ElevatorBing);
}
}
void OnTriggerExit (Collider other)
{
if (other.gameObject.tag == "Player") {
animator.SetInteger ("Open", 0);
SoldierController.dontMove = true;
}
}
}
This has been addressed. This is a bug with Unity 5 Beta - Spoke to a member of staff who provided me the latest version of Unity, which has fixed the issue.

When implementing simple Pong AI, two paddles are created and flicker

So, me being a new programmer, instead doing actual AI implementation, I used the following solution for making paddle on the right follow the ball:
if(ball.position.Y > p2.position.Y)
{
p2.position.Y += ball.position.Y;
}
else if (ball.position.Y < p2.position.Y)
{
p2.position.Y -= ball.position.Y;
}
However this happens (okay I tried taking a screencap with PrtScn and it semmed to pause the game for a microsecond and capture a single paddle instead of two flickering ones)
So what can I do to make the paddle 2 appear as one?
Full Code of Program:
Game1.cs
namespace Pong
{
public class Game1 : Game
{
//Variables
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
//Borders
Texture2D borders;
//Paddles
Paddle p1 = new Paddle();
Paddle p2 = new Paddle();
//Ball
Ball ball = new Ball();
//Positions
Vector2 bordersPos;
//Constructor
public Game1()
: base()
{
graphics = new GraphicsDeviceManager(this);
graphics.IsFullScreen = false;
graphics.PreferredBackBufferHeight = 800;
graphics.PreferredBackBufferWidth = 800;
//Content Loader
Content.RootDirectory = "Content";
}
//Initialize
protected override void Initialize()
{
base.Initialize();
}
//Load Content
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
//Assigning Textures
p1.texture = Content.Load<Texture2D>("paddle1");
p2.texture = Content.Load<Texture2D>("paddle1");
borders = Content.Load<Texture2D>("borders");
ball.texture = Content.Load<Texture2D>("ball");
//Positions
p1.position.X = 50;
p1.position.Y = graphics.GraphicsDevice.Viewport.Height / 2 - (p1.height / 2);
p2.position.X = graphics.GraphicsDevice.Viewport.Width - 50 - p2.width;
p2.position.Y = graphics.GraphicsDevice.Viewport.Height / 2 - (p2.height / 2);
bordersPos.Y = 0;
bordersPos.X = 0;
ball.position.X = 800 / 2 - ball.width / 2;
ball.position.Y = 800 / 2 - ball.height / 2;
}
protected override void UnloadContent()
{
}
//Update
protected override void Update(GameTime gameTime)
{
//Exit
if (Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
//Update Player Controls
PlayerInput();
p1.Update();
p2.Update();
ball.Update();
//Paddle Collision
if (padCol1())
{
if (ball.movingDownLeft)
{
ball.movingDownRight = true;
ball.movingDownLeft = false;
}
else if (ball.movingUpLeft)
{
ball.movingUpRight = true;
ball.movingUpLeft = false;
}
}
if (padCol2())
{
if (ball.movingDownRight)
{
ball.movingDownLeft = true;
ball.movingDownRight = false;
}
else if (ball.movingUpRight)
{
ball.movingUpLeft = true;
ball.movingUpRight = false;
}
}
//AI
if(ball.position.Y > p2.position.Y){
p2.position.Y += ball.position.Y;
}
else if (ball.position.Y < p2.position.Y)
{
p2.position.Y -= ball.position.Y;
}
base.Update(gameTime);
}
//Draw
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
//Paddles
p1.Draw(spriteBatch);
p2.Draw(spriteBatch);
//Borders
spriteBatch.Draw(borders, bordersPos, Color.White);
//Ball
ball.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
//Player Input
public void PlayerInput()
{
//Player 1
if (Keyboard.GetState(p1.pNumber).IsKeyDown(Keys.W))
{
p1.position.Y -= p1.speed;
}
else if (Keyboard.GetState(p1.pNumber).IsKeyDown(Keys.S))
{
p1.position.Y += p1.speed;
}
}
//Paddle Collision
public bool padCol1()
{
if (ball.position.Y >= p1.position.Y && ball.position.X > p1.position.X && ball.position.X < (p1.position.X + p1.width) && ball.position.Y < (p1.position.Y + p1.height))
{
return true;
}
else
return false;
}
public bool padCol2()
{
if (ball.position.Y >= p2.position.Y && ball.position.X > p2.position.X && ball.position.X < (p2.position.X + p2.width) && ball.position.Y < (p2.position.Y + p2.height))
{
return true;
}
else
return false;
}
}
}
Paddle.cs
namespace Pong
{
class Paddle : Game
{
//Variables
public Texture2D texture;
public Vector2 position;
public PlayerIndex pNumber;
public int width, height;
public float speed;
//Constructor
public Paddle()
{
texture = null;
position = Vector2.Zero;
pNumber = PlayerIndex.One;
width = 64;
height = 187;
speed = 10.0f;
}
//Update
public void Update()
{
//Set Boundaries
if (position.Y <= 30)
position.Y = 30;
if (position.Y >= 800 - 217)
position.Y = 800 - 217;
}
//Draw
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, position, Color.White);
}
}
}
Ball.cs
namespace Pong
{
class Ball : Game
{
//Variables
public Vector2 position;
public Texture2D texture;
public int width, height;
public float speed;
public bool movingDownLeft, movingUpLeft, movingDownRight, movingUpRight;
//Constructor
public Ball()
{
Content.RootDirectory = ("Content");
speed = 6.0f;
width = 20;
height = 20;
movingDownLeft = true;
movingUpRight = false;
movingUpLeft = false;
movingDownRight = false;
position = Vector2.Zero;
}
//Draw
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, position, Color.White);
}
//Update
public void Update()
{
//Directions
if(movingUpLeft){
position.Y -= speed;
position.X -= speed;
}
if (movingDownLeft)
{
position.Y += speed;
position.X -= speed;
}
if (movingUpRight)
{
position.Y -= speed;
position.X += speed;
}
if (movingDownRight)
{
position.Y += speed;
position.X += speed;
}
//Ball Wall Collision
if(movingUpLeft && position.Y <= 30)
{
movingDownLeft = true;
movingUpLeft = false;
}
//1
else if (movingDownLeft && position.X <= 0)
{
movingDownRight = true;
movingDownLeft = false;
}
//2
else if (movingUpLeft && position.X <= 0)
{
movingUpRight = true;
movingUpLeft = false;
}
//3
else if (movingDownLeft && position.Y >= 800 - 45)
{
movingUpLeft = true;
movingDownLeft = false;
}
//4
else if (movingDownRight && position.X >= 800 - width)
{
movingDownLeft = true;
movingDownRight = false;
}
//5
else if (movingUpRight && position.Y <= 30)
{
movingDownRight = true;
movingUpRight = false;
}
//6
else if (movingDownRight && position.Y >= 800 - 45)
{
movingUpRight = true;
movingDownRight = false;
}
//7
else if (movingUpRight && position.X >= 800 - width)
{
movingUpLeft = true;
movingUpRight = false;
}
}
}
}
I've never used MonoGame but this:
if(ball.position.Y > p2.position.Y)
{
p2.position.Y += ball.position.Y;
}
else if (ball.position.Y < p2.position.Y)
{
p2.position.Y -= ball.position.Y;
}
Will always overshoot, then trigger the next update.
Why don't you just do:
p2.position.Y = ball.position.Y;
EDIT: You should probably also make your input frame rate independent (unless MonoGame does this for you). It seems now you'll get higher movement speed on your paddles depending on your framerate.
Paddle and Game must not inherit from Game (GameComponent instead?). There should be only one Game object.
You should replace you booleans and complex logic with Vector2 speed describing speed of a ball, and negate its X or Y when the ball hits something.

Need some help implementing collisions in my game, with two separate classes

What I'm trying to do is to draw rectangles behind the background and make essentially collision detection. What I'm not sure however is how exactly I can implement that. I thought about making it so that as the sprite approached these rectangles, their speed would get slower and slower till they stop but would that work? Sorry if I sound a bit wet behind the ears, I'm fairly new to C# and am trying to self teach. Any help would be appreciated.
So I have a CharacterSprite class (walkingsprite) all the stuff about the frames is just a walking animation sequence I implemented.
namespace walkingsprite
{
class AnimatedSprite
{
//keyboard
KeyboardState currentKBState;
KeyboardState previousKBState;
Texture2D spriteTexture;
float timer = 0f;
float interval = 200f;
int currentFrame = 0;
int spriteWidth = 32;
int spriteHeight = 48;
int spriteSpeed = 2;
Rectangle sourceRect;
Texture2D obst;
Rectangle obst1;
Obstruction obstruction1;
Vector2 position;
Vector2 origin;
public Vector2 Position
{
get { return position; }
set { position = value; }
}
public Vector2 Origin
{
get { return origin; }
set { origin = value; }
}
public Texture2D Texture
{
get { return spriteTexture; }
set { spriteTexture = value; }
}
public Rectangle SourceRect
{
get { return sourceRect; }
set { sourceRect = value; }
}
public int SpriteSpeed
{
get { return spriteSpeed; }
set { spriteSpeed = value; }
}
public AnimatedSprite(Texture2D texture, int currentFrame, int spriteWidth, int spriteHeight)
{
this.spriteTexture = texture;
this.currentFrame = currentFrame;
this.spriteWidth = spriteWidth;
this.spriteHeight = spriteHeight;
}
public void HandleSpriteMovement(GameTime gameTime)
{
previousKBState = currentKBState;
currentKBState = Keyboard.GetState();
sourceRect = new Rectangle(currentFrame * spriteWidth, 0, spriteWidth, spriteHeight);
////////////////////////////////////////////////////////////////////
if (currentKBState.GetPressedKeys().Length == 0)
{
if (currentFrame > 0 && currentFrame < 4)
{
currentFrame = 0;
}
if (currentFrame > 4 && currentFrame < 8)
{
currentFrame = 4;
}
if (currentFrame > 8 && currentFrame < 12)
{
currentFrame = 8;
}
if (currentFrame > 12 && currentFrame < 16)
{
currentFrame = 12;
}
}
////////////////////////////////////////////////////////////////////
//sprintin
if (currentKBState.IsKeyDown(Keys.Space))
{
spriteSpeed = 2;
interval = 100;
}
else
{
spriteSpeed = 1;
interval = 200;
}
///////////////////////////////////////////////
if (currentKBState.IsKeyDown(Keys.Down) == true)
{
AnimateDown(gameTime);
if (position.Y < 575)
{
position.Y += spriteSpeed;
}
}
////////////////////////////////////////////////////
if (currentKBState.IsKeyDown(Keys.Up) == true)
{
AnimateUp(gameTime);
if (position.Y > 25)
{
position.Y -= spriteSpeed;
}
}
//////////////////////////////////////////////////////////
if (currentKBState.IsKeyDown(Keys.Right) == true)
{
AnimateRight(gameTime);
if (position.X < 780)
{
position.X += spriteSpeed;
}
}
////////////////////////////////////////////////////////////////////
if (currentKBState.IsKeyDown(Keys.Left) == true)
{
AnimateLeft(gameTime);
if (position.X > 0)
{
position.X -= spriteSpeed;
}
}
origin = new Vector2(sourceRect.Width / 2, sourceRect.Height / 2);
}
////////////////////////////////////////////////////////////////////
public void AnimateRight(GameTime gameTime)
{
if (currentKBState != previousKBState)
{
currentFrame = 9;
}
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
if(timer > interval)
{
currentFrame++;
if(currentFrame > 11)
{
currentFrame = 8;
}
timer = 0f;
}
}
////////////////////////////////////////////////////////////////////
public void AnimateUp(GameTime gameTime)
{
if (currentKBState != previousKBState)
{
currentFrame = 13;
}
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
if (timer > interval)
{
currentFrame++;
if (currentFrame > 15)
{
currentFrame = 12;
}
timer = 0f;
}
}
//////////////////////////////////////////
public void AnimateDown(GameTime gameTime)
{
if (currentKBState != previousKBState)
{
currentFrame = 1;
}
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
if (timer > interval)
{
currentFrame++;
if (currentFrame > 3)
{
currentFrame = 0;
}
timer = 0f;
}
}
////////////////////////////////////////////////////
public void AnimateLeft(GameTime gameTime)
{
if (currentKBState != previousKBState)
{
currentFrame = 5;
}
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
if (timer > interval)
{
currentFrame++;
if (currentFrame > 7)
{
currentFrame = 4;
}
timer = 0f;
}
}
}
}
And I have an obstruction class.
namespace walkingsprite
{
class Obstruction
{
Texture2D obst;
Rectangle obstRec1;
public Rectangle ObstRec1
{
get { return obstRec1; }
set { obstRec1 = value; }
}
public Texture2D Obst
{
get { return obst; }
set { obst = value; }
}
public Obstruction(Texture2D texture, Rectangle rec)
{
this.obstRec1 = rec;
this.obst = texture;
}
}
}
XNA already have a Rectangle class with a method to return if a rectangle collide with another rectangle.
An exemple:
Rectangle rec1 = new Rectangle(0, 0, 10, 10);
Rectangle rec2 = new Rectangle(5, 5, 10, 10);
rec1.Intersects(rec2); //Return true if a rectangle intersects another one
What people normally do, is a List of Rectangle and test one by one to know if they collide, or they implements a QuadTree but that is a bit more difficult in the beginning.
An exemple of a List of Rectangle:
List<Rectangle> allObjects = new List<Rectangle>();
Rectangle rec1 = new Rectangle(0, 0, 10, 10);
Rectangle rec2 = new Rectangle(10, 15, 10, 10);
Rectangle mainCharRec = new Rectangle(10, 20, 10, 10);
allObjects.Add(rec1);
allObjects.Add(rec2);
To test if main character rectangle intersects some other rectangles you can do a method with a foreach like this:
foreach (Rectangle rec in allObjects)
if(mainCharRec.Intersects(rec))
return true;
return false;
About getting slower, I think you could have a rectangle to the object and another to the "close region", and when the character enter in the region you slow his speed by the distance you give to the region, for example, if you have a rectangle with 10 pixels larger for each side, when character collides with larger rectangle he loses spriteSpeed/10 for step, until he stops. When the value is too much low, it turn 0:
if (spriteSpeed < 0.5)
spriteSpeed = 0;
else
spriteSpeed -= spriteSpeed/10;

Categories