Camera collision in unity - c#

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.

Related

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.

Mouse axes are based on position, not movement

Basically, when I have my cursor in the center of the screen, the camera doesn't rotate. Pretty standard. However, If I move my cursor to the left or right, It will start rotating. Still makes sense. However, When I stop moving the cursor, the rotation continues. I'm using an empty object and making the camera face in the same direction as that empty object. The problem is, the object continues to rotate. If I move the cursor back to the center of the screen, it stops rotating again. Something similar happens when I assign axes in the project settings to the right stick on an Xbox 1 controller. If I move the stick right, the camera begins to rotate, however, if I return the stick to the deadzone, it continues to rotate. If I then move the stick left, it will slow down the rotation, and eventually begin rotating the other direction. It doesn't happen with the vertical stick axis, though.
Here's my code with the mouse for the player and empty object rotation:
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public Transform PlayerT;
public Transform camT;
public Transform CamR;
public CharacterController controller;
public float speed;
public float CamRSpeed;
private float gravity;
private float HorizontalR;
private float VerticalR;
private Vector3 moveDirection;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
HorizontalR = Input.GetAxis("Mouse X") * CamRSpeed * Time.deltaTime;
VerticalR = Input.GetAxis("Mouse Y") * CamRSpeed * Time.deltaTime;
CamR.Rotate(VerticalR, HorizontalR, 0f);
PlayerT.forward = CamR.forward;
PlayerT.eulerAngles = new Vector3(0f, PlayerT.eulerAngles.y, 0f);
moveDirection = (PlayerT.forward * Input.GetAxis("Vertical") * speed) + (PlayerT.right * Input.GetAxis("Horizontal") * speed);
controller.Move(moveDirection * Time.deltaTime);
}
}
//and for the camera (this is a separate script, I'm just not entirely sure how this site's formatting works):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraScript : MonoBehaviour
{
public Transform cam;
public Transform player;
public Transform CamR;
private Vector3 offset;
// Start is called before the first frame update
void Start()
{
offset = CamR.position - cam.position;
}
// Update is called once per frame
void Update()
{
cam.eulerAngles = new Vector3(CamR.eulerAngles.x, CamR.eulerAngles.y, 0f);
cam.position = CamR.position - (CamR.rotation * offset);
}
}```
Well, as it turns out, it was simply because the object I was trying to rotate was a child of the player. I'm not entirely sure why it didn't work, but it does now.

Fly swatter movement in Unity

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)

Unity2D - Companion

When reading this, keep in mind I'm new to both programming and Unity, so I might be missing some terms or tools Unity offer. Please elaborate your answers in an ELI5 manner. Thanks in advance!
I am currently working on some game-physics for a small personal project. Currently I've created a platform, a character and what should be, a following companion.
However, since I'm still not on a level, where I can create perfect code on own hand, I found an "enemy" script and tried to modify it a bit.
It Works to an extend, but it needs some tweaks which I hope I can help aquire with you guys.
This is how it looks now (the orange square is the companion)
It follows the player, and I can tweak the speed to fit as a companion, and not a player. However, as the Picture presents, the companion runs for the center of the player. What I want to create is a companion which follows the player, but still keeps a small gap from the player.
My first thoughts was to create some kind of permanent offset, but I fail to figure out how to do this without messing up the follow function.
I hope you can help me, it will be much appreciated!
Here's the code for reference.
Code attached to Player:
using UnityEngine;
using System.Collections;
public class PlayerCompanion : MonoBehaviour
{
//In the editor, add your wayPoint gameobject to the script.
public GameObject wayPoint;
//This is how often your waypoint's position will update to the player's position
private float timer = 0.5f;
void Update ()
{
if (timer > 0) {
timer -= Time.deltaTime;
}
if (timer <= 0) {
//The position of the waypoint will update to the player's position
UpdatePosition ();
timer = 0.5f;
}
}
void UpdatePosition ()
{
//The wayPoint's position will now be the player's current position.
wayPoint.transform.position = transform.position;
}
}
Code attached to companion:
using UnityEngine;
using System.Collections;
public class FollowerOffset : MonoBehaviour {
//You may consider adding a rigid body to the zombie for accurate physics simulation
private GameObject wayPoint;
private Vector3 wayPointPos;
//This will be the zombie's speed. Adjust as necessary.
private float speed = 10.0f;
void Start ()
{
//At the start of the game, the zombies will find the gameobject called wayPoint.
wayPoint = GameObject.Find("wayPoint");
}
void Update ()
{
wayPointPos = new Vector3(wayPoint.transform.position.x, transform.position.y, wayPoint.transform.position.z);
//Here, the zombie's will follow the waypoint.
transform.position = Vector3.MoveTowards(transform.position, wayPointPos, speed * Time.deltaTime);
}
}
bump, I guess ? :)
You can use smooth follow script. I have created a sample class for you. This class has features to follow any given gameobject with some delay and offset. You will have to tweak some values according to your need.
using UnityEngine;
using System.Collections;
public class PlayerCompanion : MonoBehaviour
{
[SerializeField]
private GameObject wayPoint;
[SerializeField]
public Vector3 offset;
public Vector3 targetPos;//Edit: I forgot to declare this on firt time
public float interpVelocity;
public float cameraLerpTime = .1f;
public float followStrength = 15f;
// Use this for initialization
void Start ()
{
//At the start of the game, the zombies will find the gameobject called wayPoint.
wayPoint = GameObject.Find("wayPoint");
offset = new Vector3 (5,0,0);//input amount of offset you need
}
void FixedUpdate () {
if (wayPoint) {
Vector3 posNoZ = transform.position;
Vector3 targetDirection = (wayPoint.transform.position - posNoZ);
interpVelocity = targetDirection.magnitude * followStrength;
targetPos = transform.position + (targetDirection.normalized * interpVelocity * Time.deltaTime);
transform.position = Vector3.Lerp (transform.position, targetPos + offset, cameraLerpTime);
}
}
}
Attach this class to your player companion, play with different values.
To preserve object orientation your companion schould not be anyways child of your main character.
Your wayPoint doesn't needs to be a GameObject but a Transform instead and your code will looks like better.
If your game is a 2D platform your and your companion needs to be backwards your player it probabli applys to just one axis (X?) so you can decrement your waiPoint in a more directly way by calculating it on your UpdatePosition function like this:
wayPoint.position = transform.position * (Vector3.left * distance);
where your "distance" could be a public float to easily setup.
so on your companion script Update just do:
transform.position = Vector3.MoveTowards(transform.position, wayPoint.position, speed * Time.deltaTime);
I can't test it right now so you could have problems with Vector3 multiply operations, just comment and I'll try to fix as possible ;)

Unity 2d jumping script

Does anyone have a good jumping script for 2d games in unity? The code I have works but still is far from jumping, it looks like it is flying.
using UnityEngine;
using System.Collections;
public class movingplayer : MonoBehaviour {
public Vector2 speed = new Vector2(10,10);
private Vector2 movement = new Vector2(1,1);
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float inputX = Input.GetAxis ("Horizontal");
float inputY = Input.GetAxis ("Vertical");
movement = new Vector2(
speed.x * inputX,
speed.y * inputY);
if (Input.GetKeyDown ("space")){
transform.Translate(Vector3.up * 260 * Time.deltaTime, Space.World);
}
}
void FixedUpdate()
{
// 5 - Move the game object
rigidbody2D.velocity = movement;
//rigidbody2D.AddForce(movement);
}
}
Usually for jumping people use Rigidbody2D.AddForce with Forcemode.Impulse. It may seem like your object is pushed once in Y axis and it will fall down automatically due to gravity.
Example:
rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
The answer above is now obsolete with Unity 5 or newer. Use this instead!
GetComponent<Rigidbody2D>().AddForce(new Vector2(0,10), ForceMode2D.Impulse);
I also want to add that this leaves the jump height super private and only editable in the script, so this is what I did...
public float playerSpeed; //allows us to be able to change speed in Unity
public Vector2 jumpHeight;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
transform.Translate(playerSpeed * Time.deltaTime, 0f, 0f); //makes player run
if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space)) //makes player jump
{
GetComponent<Rigidbody2D>().AddForce(jumpHeight, ForceMode2D.Impulse);
This makes it to where you can edit the jump height in Unity itself without having to go back to the script.
Side note - I wanted to comment on the answer above, but I can't because I'm new here. :)
Use Addforce() method of a rigidbody compenent, make sure rigidbody is attached to the object and gravity is enabled,
something like this
gameObj.rigidbody2D.AddForce(Vector3.up * 10 * Time.deltaTime); or
gameObj.rigidbody2D.AddForce(Vector3.up * 1000);
See which combination and what values matches your requirement and use accordingly.
Hope it helps

Categories