GameObject reflecting off another gameObject error - c#

I am new at Unity/c# and I wanted to make a pong game. I made this by watching a tutorial on youtube. There is no "error" except the ball doesn't move after touching the player.
This is ball code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallCode : MonoBehaviour
{
private Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Vector2 position = transform.position;
position.x = position.x - 5.8f * Time.deltaTime;
transform.position = position;
}
}
This is ball bounce code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallBounce : MonoBehaviour
{
private Rigidbody2D rb;
Vector3 lastVelocity;
// Start is called before the first frame update
void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
lastVelocity = rb.velocity;
}
private void OnCollisionEnter2D(Collision2D coll)
{
var speed = lastVelocity.magnitude;
var direction = Vector3.Reflect(lastVelocity.normalized, coll.contacts[0].normal);
}
}
And this is player code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float moveSpeed = 4.5f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float vertical = Input.GetAxis("Vertical");
Vector2 position = transform.position;
position.y = position.y + moveSpeed * vertical * Time.deltaTime;
transform.position = position;
}
}
When I play the game the ball will collide with player, but it won't ricochet.

Your OnCollisionEnter2D method is not doing anything except set local variables that are quickly discarded. You need to make speed and direction variables of the BallCode or BallBounce class, then set up the BallCode class to use those variables in Update() when determining the motions it makes.

You can try adding a 2D rigid body property to the sphere and removing gravity.
Add a C# script to control the movement of the ball and add a 2D collider to the ball.
//Initial velocity
public float speed = 100f;
void Start()
{
this.GetComponent<Rigidbody2D>().AddForce
(Vector2.right * speed);
}
Add a 2D collider:
Add a 2D physical material to the sphere, so that the ball can bounce.
Modify 2D Physical Material Properties.
Added to the sphere's material.
Add player (Square) and control player movement script.
void Update()
{
// The mouse moves with the player
float y = Camer.main.ScreenToWorldPoint
(Input.mousePosition).y
this.transform.position = new Vector3
(transform.position.x,y,0);
}
Add the wall around the screen and the script Wall to control the randomness of the vertical speed and the direction of the ball when the ball collides with the wall.
public class Wall : MonoBehaviour
{
//Initial velocity
public float speed = 100f;
// Triggered when the collision ends
private void OnCollisionExit(Collision2D collision)
{
int r = 1;
if(Random.Range(0, 2) != -1)
{
r *= -1;
}
//add a vertical force
collision.gameObject.GetComponent<Rigidbody2D>().
AddForce(Vector2.up.*speed*r);
}
}
achieve effect:

Related

Unity 2d Input lag

I'm making a 2d open world game with physics similar to that of stardew valley, but for some reason there's a lot of input lag on the character even when I remove all the other scripts and animations.
I even tried removing most of the sprites such as houses and whatnot but it still has a lot of lag, not framerate lag, just the player movement.
I will attempt to explain: If you just lightly tap the keyboard the player moves and stops just fine, but if you hold down the button then let go (for about 5s gives the most lag, doesn't get any worse after that), the player keeps moving a little after you let go of the key.
Here's the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovementControls : MonoBehaviour {
public float speed;
private Vector2 MoveSpeed;
private Rigidbody2D Player;
void Start() {
Player = GetComponent<Rigidbody2D>();
}
void Update() {
Vector2 PlayerInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
MoveSpeed = PlayerInput.normalized * speed;
}
void FixedUpdate() {
Player.MovePosition(Player.position + MoveSpeed * Time.fixedDeltaTime);
}
}
Anyone know how to fix this?
Here's what fixed the problem to anyone else with said problem:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovementControls : MonoBehaviour {
public float speed; //Change the player's speed
private Vector2 MoveSpeed; //This is what the player's speed will be set to after some math
private Rigidbody2D Player; //The player
void Start() {
Player = GetComponent<Rigidbody2D>(); //Find the player GameObject
}
void Update() {
Vector2 PlayerInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")); //Get input
MoveSpeed = PlayerInput * speed; //Math
Player.MovePosition(Player.position + MoveSpeed * Time.fixedDeltaTime); //Move the player
}
}

sphere collider collid shoot player ship?

Okay, I made some progress with the look towards me I'm able to get the enemy ship to follow the player and the laser guns as well could use some guidance how to get the laser to kill the player ship and prompt the lose and the 'R' for restart messages Aanty insight how to go about it is welcomed.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyManagement : MonoBehaviour
{
[SerializeField] GameObject deathFX;
[SerializeField] Transform parent;
// The target marker.
[SerializeField] Transform target;
// Angular speed in radians per sec.
[SerializeField] float speed;
// Start is called before the first frame update
void Start()
{
AddSphereCollider();
}
private void AddSphereCollider()
{
Collider sphereCollider = gameObject.AddComponent<SphereCollider>();
sphereCollider.isTrigger = false;
}
void Update()
{
Vector3 targetDir = target.position - transform.position;
// The step size is equal to speed times frame time.
float step = speed * Time.deltaTime;
Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0f);
Debug.DrawRay(transform.position, newDir, Color.red);
// Move our position a step closer to the target.
transform.rotation = Quaternion.LookRotation(newDir);
}
}
You need to give it a radius for collision detection.
sphereCollider.radius = 10.0f;

How to shoot ball to Touch X position Unity 3D?

I have a ball on a ground, and when touching the screen I want to shoot it to the X position of the Touch. Do you have any suggestions?
This is the code I have so far:
public Rigidbody Ball;
public float Speed = 50f;
void FixedUpdate () {
if(ClickDone == false){
if (Input.GetMouseButton(0)){
ClickDone = true;
Ball.velocity = transform.forward * Speed;
}
}
}
here is your new code :
using UnityEngine;
public class GoToTouch : MonoBehaviour
{
public Camera cam;//put your main camera here
public float speed;//Speed of movement
Vector3 LastTouch;
void Start()
{
LastTouch = Vector3.zero;
}
void Update()
{
//We check for new touches etch frame
if (Input.touchCount> 0)
LastTouch = Input.touches[0].rawPosition;
//We move towards the last touch
if(LastTouch != Vector3.zero)transform.position=
Vector3.Lerp(transform.position,cam.ScreenToWorldPoint(LastTouch),speed*Time.DeltaTime);
}
}
what is important for you to look at is the
ScreenToWorldPoint function LastTouch holds the actual pixel the user touched
after ScreenToWorldPoint you get the position that the pixel he touched represent in the
world. Good luck learning !

How can I make the npc character to rotate slowly facing the player while changing animator transitions?

I have in the soldier animator a Grounded transition and this is start with this transition by default. Then I did that after 3 second it will slowly change between the two transitions from Grounded to Rifle_Aiming_Idle.
But To see how it's working and if it's working good like I wanted I had to turn off the FPSController Camera( FPSCamera is turned off gray ). So when running the game the active camera is the Main Camera and the CM vcam1 ( Cinemachine virtual camera ).
But I want to make more with this cutscene.
I want that first the cutscene will start only when the player the FPSController will exit a door:
This script is attached to the FPSController:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;
public class SpaceshipCutscene : MonoBehaviour
{
public Transform player;
public Transform npc;
public float cutsceneDistance = 5f;
public float speed;
private bool moveNpc = false;
// Use this for initialization
void Start()
{
}
private void Update()
{
if (moveNpc)
{
float travel = Mathf.Abs(speed) * Time.deltaTime;
Vector3 direction = (player.position - npc.position).normalized;
Quaternion lookrotation = Quaternion.LookRotation(direction);
npc.rotation = Quaternion.Slerp(npc.rotation, lookrotation, Time.deltaTime * 5);
Vector3 position = npc.position;
position = Vector3.MoveTowards(position, player.position, travel);
npc.position = position;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.name == "Horizontal_Doors_Kit")
moveNpc = true;
}
}
I want that when the player the FPSController exit the door start the cutscene and while it's playing/doing the cutscene I want at the same time also making the soldier with the animator to rotate slowly facing the FPSController.
FPSController exit the door > Soldier changing slowly from grounded to aiming mode and Soldier rotating slowly facing the FPSController.
My problems are how to start the cinemachine cutscene when the FPSController exit the door and how to make the Soldier( npc ) to rotate slowly facing the FPSController.
What I tried in the Update in the script is not working good.
It's making the npc moving and not rotating slowly good enough fro the cutscene like I wanted.
And maybe for the rotation part I should use the Cinemachine and not doing it in the script ? Maybe I should using Timeline here too for the rotation part ?
Working solution for what I needed:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;
public class SpaceshipCutscene : MonoBehaviour
{
public Transform player;
public Transform npc;
public Camera FPSCamera;
public Camera mainCamera;
public Animator anim;
public float rotationSpeed = 3f;
private bool moveNpc = false;
// Use this for initialization
void Start()
{
}
private void Update()
{
if (moveNpc)
{
Vector3 dir = player.position - npc.position;
dir.y = 0; // keep the direction strictly horizontal
Quaternion rot = Quaternion.LookRotation(dir);
// slerp to the desired rotation over time
npc.rotation = Quaternion.Slerp(npc.rotation, rot, rotationSpeed * Time.deltaTime);
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.name == "Horizontal_Doors_Kit")
{
FPSCamera.enabled = false;
mainCamera.enabled = true;
moveNpc = true;
anim.SetTrigger("SoldierAimingTrigger");
}
}
}

How to add force to an object after a collision in unity2d, to simulate hitting a baseball with a bat

I am working on a 2D game project. I would like the user to be able to hit the ball when he presses on the "space" key. I assigned;
Circle collider 2D & Rigidbody 2D to the ball
Rigidbody 2D & Box Collider 2D to the hero
Edge Collider 2D to the baseball bat.
Here is my script which I have called "KickTheBall.cs":
using UnityEngine;
using System.Collections;
public class KickTheBall : MonoBehaviour {
public float bounceFactor = 0.9f; // Determines how the ball will be bouncing after landing. The value is [0..1]
public float forceFactor = 10f;
public float tMax = 5f; // Pressing time upper limit
private float kickStart; // Keeps time, when you press button
private float kickForce; // Keeps time interval between button press and release
private Vector2 prevVelocity; // Keeps rigidbody velocity, calculated in FixedUpdate()
[SerializeField]
private EdgeCollider2D BatCollider;
private Rigidbody2D rb;
void Start () {
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate () {
if(kickForce != 0)
{
float angle = Random.Range(0,20) * Mathf.Deg2Rad;
rb.AddForce(new Vector2(0.0f,
forceFactor * Mathf.Clamp(kickForce, 0.0f, tMax) * Mathf.Sin(angle)),
ForceMode2D.Impulse);
kickForce = 0;
}
prevVelocity = rb.velocity;
}
void Update(){
if(Input.GetKeyDown (KeyCode.Space))
{
kickStart = Time.time;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if(hit.collider.name == "Ball") // Rename ball object to "Ball" in Inspector, or change name here
kickForce = Time.time - kickStart;
}
}
}
public void KickBall(){
BatCollider.enabled = true;
}
void OnCollisionEnter(Collision col)
{
if(col.gameObject.tag == "Ground") // Do not forget assign tag to the field
{
rb.velocity = new Vector2(prevVelocity.x,
-prevVelocity.y * Mathf.Clamp01(bounceFactor));
}
}
}
However, I am unable to kick the ball when I press the space key. The ball is just bouncing because of colliders. What am I missing?
Check my result:
I would advocate something more like this to start with. This is the script you would add onto your baseball bat.
Part 1:
using UnityEngine;
using System.Collections;
public class KickTheBall : MonoBehaviour
{
public float forceFactor = 10f;
private float kickForce = 50f;
void OnCollisionEnter(Collision col)
{
if(col.gameObject.tag == "Ball") // Do not forget assign tag to the field
{
rb = col.gameobject.GetComponent<Rigidbody>();
rb.AddForce(transform.right * kickForce);
}
}
}
I have simplified your AddForce function for demonstration purposes. Feel free to replace it with your more complex AddForce function if everything is working.
Part 2:
If you really want to include the part where holding the space button makes the hit stronger, then add this:
void Update()
{
if(Input.GetKey(KeyCode.Space))
{
kickForce += 0.5f;
}
}
and add at the end of the oncollisionenter
kickForce = 0;
What this will do is build up force while you hold the space button down. After a successful hit the force will reset to 0. So subsequent collisions will not result in a hit until the space button is held again.
Let me know if this did anything for you.
I solved the issue with the help of #TylerSigi. I updated my script file with these codes:
using UnityEngine;
using System.Collections;
public class KickTheBall : MonoBehaviour {
public float forceFactor = 10f;
private float kickForce = 0f;
private EdgeCollider2D BatCollider;
public GameObject Ball;
void Start () {
}
void Update()
{
if (Input.GetKey (KeyCode.Space)) {
kickForce = 1000;
} else {
kickForce = 0;
}
}
void OnTriggerEnter2D(Collider2D col)
{
if(col.gameObject.tag == "Enemy") // Do not forget assign tag to the field
{
Ball.GetComponent<Rigidbody2D>().AddForce(transform.right * kickForce);
}
}
}

Categories