Fly swatter movement in Unity - c#

I am creating a game on unity (my first 2D game) and the idea of this game is to kill a fly using swatter but the problem is in the fly movement (top to down) and the collision between the swatter and the fly.
This is my code but I don't know why the collision doesn't work
using UnityEngine;
using System.Collections;
public class SwatterController : MonoBehaviour {
public float speed = 1.5f;
private Vector3 target;
void Start () {
target = transform.position;
}
void Update () {
//Movement of swatter when I click on the screen
if (Input.GetMouseButtonDown(0)) {
target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
target.z = transform.position.z;
}
transform.position = Vector3.MoveTowards(transform.position, target, speed * 5);
}
void OnCollisionEnter2D(Collision2D other){
Debug.Log ("dead");
}
}
and I would like to know how correct my code to get right movement of the swatter( the fly swatter is placed behind the camera)
and if you have an example please post it.
Objects used : Fly( circle collider 2D) , swatter(box collider 2D)

Related

Camera collision in unity

i can't figure out how to check for collision, here is my camera-movement script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cameracontroller : MonoBehaviour
{
public float movementSpeed;
public float movementTime;
public Vector3 newPosition;
// Start is called before the first frame update
void Start()
{
newPosition = transform.position;
}
// Update is called once per frame
void Update()
{
HandleMovementInput();
}
void HandleMovementInput()
{
if(Input.GetKey(KeyCode.W))
{
newPosition += (transform.forward * movementSpeed);
}
if(Input.GetKey(KeyCode.S))
{
newPosition += (transform.forward * -movementSpeed);
}
if(Input.GetKey(KeyCode.D))
{
newPosition += (transform.right * movementSpeed);
}
if(Input.GetKey(KeyCode.A))
{
newPosition += (transform.right * -movementSpeed);
}
transform.position = Vector3.Lerp(transform.position, newPosition, Time.deltaTime * movementTime);
}
}
I've tried using void OnCollisionEnter(Collision collision) but didn't seem to work, am i doing something wrong? All object have colliders and i have also tried using rigidbody. I am still a beginner programmer and only code in my spare time, to explain my lack of knowledge.
OnCollisionEnter is a bit tricky, I believe you get the best result with it when it is interacting with dynamic Rigidbodies (i.e not kinematic). If you want it to check for collision with say walls, in which case neither the camera nor the walls have dynamic rigidbodies, then just use OnTriggerEnter.
If you're trying to make a RPG styled character controller and the camera collision code is to help prevent camera clipping through walls, then I believe you can get the job down with raycast (by shooting a raycast from camera towards the player) instead of using OnTrigger.

How to tell a Unity object to move forward in the direction of each of its parent object's axes?

I've used a simple Unity tutorial to make a Space Invaders game, but I want to adapt it into a different game.
The tutorial made a right-and-left control of the player ship, but I changed it to rotational control (which took a while because for some reason almost no script correctly confined the rotation to the boundaries I've set).
After scripting the rotation, I wanted the shots to move forward on the screen in the direction of the axis to which it is spawned. The axis is of an empty child object inside the ship object, so its own angles are always set to 0.
I saw the original function controlling the bullet movement:
bullet.position += Vector3.up * speed;
still moves it up the screen regardless of how the bullet is rotated.
So I tried:
bullet.position += Vector3.forward * speed;
and saw it moves the bullet into the Z axis.
Basically I'm asking is whether there's a sub-function of Vector3 I'm missing which moves an object according to the direction of its own axis?
Here are the codes of the two classes:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShotSpawner : MonoBehaviour
{
public GameObject shot;
public Transform shotSpawn;
public float fireRate;
private float nextFire;
// Start is called before the first frame update
void Start()
{
}
void Update()
{
if (Input.GetButton("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(shot, shotSpawn.position, shotSpawn.rotation);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletController : MonoBehaviour
{
private Transform bullet;
public float speed;
// Start is called before the first frame update
void Start()
{
bullet = GetComponent<Transform>();
}
void FixedUpdate()
{
bullet.position += Vector3.up * speed;
if (bullet.position.y >= 10)
Destroy(gameObject);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Enemy")
{
Destroy(other.gameObject);
Destroy(gameObject);
PlayerScore.playerScore++;
}
else if (other.tag == "Base")
Destroy(gameObject);
}
}
I found the simple solution
The code required
transform.up
Rather than
Vector3.up
Transform goes by the objects axis while Vector3 goes by the world space.

how to make unity2d point-and-click movement smooth?

I have a rectangle player sprite with a Box Collider 2D and a Rigidbody2D attached. I also have a script for point-and-click movement attached to the player object (i.e. player moves to mouse click position). However as soon as the player character hits a collider, it starts to jitter rather than just fully stop. I don't know a lot about Unity physics other than what I've picked up in a few tutorials, so I'll include as much relevant information as I can.
The Rigidbody 2D component has all forces set to 0, except for mass being 0.0001. The body type is dynamic, and collision detection is set to continuous. My movement script looks like this, got it straight from a tutorial:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControls : MonoBehaviour
{
public float speed = 1;
private Vector3 target;
void Start()
{
target = transform.position;
}
void Update()
{
if (Input.GetMouseButtonDown(0)) {
target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
target.z = transform.position.z;
}
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
}
Is there an easier way to implement smooth point-and-click movement?

Unity game trouble

I am creating a game in Unity where I have to have a player (a ball) and three enemies (in this case three rotating cylinders). Whenever the player hits an enemy, I need it to die (which I have already done) and then print out Game over, which I don't know how to do. I also need the player to respawn after it dies, which is another think I don't know how to do. I also need to create three "virtual holes" where when the player rolls over them, it respawns, but not dies. I figure I can simulate holes by creating flat cylinders, but I don't know how to make the ball respawn but rolling over them. Thank you in advance!! Please be clear about which part does what in your answer.
//My player script
public class PlayerController : MonoBehaviour
{
public float speed;
private Rigidbody rb;
public float threshold;
public Text gameOver;
// Use this for initialization
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
//rolls the player according to x and z values
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed);
}
}
//my script that makes the enemy rotate and kills the player but after the
player dies it just disappears
public class Rotater : MonoBehaviour {
public Text gameOver;
// Update is called once per frame
void Update ()
{
transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
}
//kills player
void OnCollisionEnter(Collision Col)
{
if (Col.gameObject.name == "Player")
{
Destroy(Col.gameObject);
gameOver.text = "Game over!";
}
}
//my script that respawns the play if it falls off the maze
public class Respawn : MonoBehaviour
{
// respawns player if it goes below a certain point (falls of edge)
public float threshold;
void FixedUpdate()
{
if (transform.position.y < threshold)
transform.position = new Vector3(-20, 2, -24);
}
}
You need to create a UI to draw text over your game. You can learn about it here.
When you have the UI in place, you can just activate/deactivate the relevant parts with SetActive(bool).
To kill and respawn the player, I suggest you not to destroy it and re-instantiate it. Instead, you can simply deactivate it and reactivate it in the new position using SetActive(bool) again.
For the holes, you can create other objects with colliders and use OnCollisionEnter as you already did but to change player's position.

Unity3d OnTriggerEnter2D not firing

I'm currently trying to make a Unity3d (Or 2D in this case) Platformer tech demo.
While working on the demo I ran into a bit of a snag because I want my Player object to be able to go up slopes, but if I apply gravity while the Player object is on the ground it will not be able to go up slopes, even if it can go down them. My solution was to turn off gravity while the PLayer object was touching the ground, and turn it back on when it wasn't. I did this by using the functions void OnCollisionEnter2D(Collision2D collision) to turn the gravity off, and void OnCollisionExit2D(Collision2D collision) to turn it back on.
This did not work, so I played with it a bit and thought of the idea to give the ground, and Player object "Trigger Boxes" which are unseen child Cube objects that have a Collider marked as a Trigger. So now I am using the function void OnTriggerEnter2D(Collider2D collision) to turn the gravity off, and void OnTriggerExit2D(Collider2D collision) to turn it back on. But this also does not work. Below is my code, first is the Player object's main script, and after that is the Player object's "TriggerBox" and after that will be images to show how my objects are setup in Unity.
The result: The Player class currently does not collide with the ground, and falls through it to infinity.
What I want: The player to collide with the ground, and the player's TriggerBox to collide with the ground's "TriggerBox" and turn off the Player's gravity.
Notes: I've tried giving the players, and ground RigidBody2Ds. The player collides with the ground and gets jittery, and does not trigger the gravity turn-off, and the ground falls on contact with the player when the ground has the RigidBody2D. It is unknown what triggers, as the ground falls right under the player.
using UnityEngine;
using System.Collections;
public class PlayerControls : MonoBehaviour {
CharacterController controller;
private float speed = 0.004f;
private float fallSpeed = 0.01f;
private Vector3 tempPos;
bool onGround = false;
public void setOnGround(bool b){ onGround = b; }
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
tempPos = Vector3.zero;
if(Input.GetKey(KeyCode.W)) tempPos.y -= speed;
if(Input.GetKey(KeyCode.S)) tempPos.y += speed;
if(Input.GetKey(KeyCode.A)) tempPos.x -= speed;
if(Input.GetKey(KeyCode.D)) tempPos.x += speed;
RaycastHit2D[] hits = Physics2D.RaycastAll(new Vector2(transform.position.x,transform.position.y), new Vector2(0, -1), 0.2f);
float fallDist = -fallSpeed;
if(hits.Length > 1){
Vector3 temp3Norm = new Vector3(hits[1].normal.x, hits[1].normal.y, 0);
Vector3 temp3Pos = new Vector3(tempPos.x, tempPos.y, 0);
temp3Pos = Quaternion.FromToRotation(transform.up, temp3Norm) * temp3Pos;
tempPos = new Vector2(temp3Pos.x, temp3Pos.y);
}
if(!onGround) tempPos.y = fallDist;
transform.Translate(tempPos);
}
}
Next the TriggerBox:
using UnityEngine;
using System.Collections;
public class PlayerTriggerBox : MonoBehaviour {
public PlayerControls playerControls;
// Use this for initialization
void Start () {
//playerControls = gameOGetComponent<PlayerControls>();
if(playerControls == null) Debug.Log("playerControls IS NULL IN PlayerTriggerBox!");
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter2D(Collider2D other) {
playerControls.setOnGround(true);
}
void OnTriggerExit2D(Collision2D collision){
playerControls.setOnGround(false);
}
}
-As for the images for my setup-
The player's setup:
The player's TriggerBox setup:
The ground's setup:
The ground's TriggerBox setup:
Thank you for your time reading this, and hopefully for your help.

Categories