How to shoot ball to Touch X position Unity 3D? - c#

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 !

Related

GameObject reflecting off another gameObject error

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:

How to respawn a paddle and ball in breakout - Unity 3D C#

I'm making a breakout game in 3D and it's my first time making a game and using Unity so I'm a bit clueless. I've got to the point where my game works fine up until the ball goes off the screen and into the "dead zone".
Can someone advise how to respawn the paddle and ball together and carry on with the game?
I've included my ball and paddle scripts below, I have a script for the bricks as well but not sure that was relevant. I also made a prefab of the ball and paddle together but no idea what to do with it.
Thanks to anyone who can help :)
Code for my ball
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallScript : MonoBehaviour
{
public Rigidbody rbody;
public float MinVertMovement = 0.1f;
public float MinSpeed = 10f;
public float MaxSpeed = 10f;
private bool hasBeenLaunched = false;
void Start()
{
}
private float minVelocity = 10f;
private Vector3 lastFrameVelocity;
void FixedUpdate()
{
if (hasBeenLaunched == false)
{
if (Input.GetKey(KeyCode.Space))
{
Launch();
}
}
if (hasBeenLaunched)
{
Vector3 direction = rbody.velocity;
direction = direction.normalized;
float speed = direction.magnitude;
if (direction.y>-MinVertMovement && direction.y <MinVertMovement)
{
direction.y = direction.y < 0 ? -MinVertMovement : MinVertMovement;
direction.x = direction.x < 0 ? -1 + MinVertMovement : 1 - MinVertMovement;
rbody.velocity = direction * MinSpeed;
}
if (speed<MinSpeed || speed>MaxSpeed)
{
speed = Mathf.Clamp(speed, MinSpeed, MaxSpeed);
rbody.velocity = direction*speed;
}
}
lastFrameVelocity = rbody.velocity;
}
void OnCollisionEnter(Collision collision)
{
Bounce(collision.contacts[0].normal);
}
private void Bounce(Vector3 collisionNormal)
{
var speed = lastFrameVelocity.magnitude;
var direction = Vector3.Reflect(lastFrameVelocity.normalized, collisionNormal);
Debug.Log("Out Direction: " + direction);
rbody.velocity = direction * Mathf.Max(speed, minVelocity);
}
public void Launch()
{
rbody = GetComponent<Rigidbody>();
Vector3 randomDirection = new Vector3(-5f, 10f, 0);
randomDirection = randomDirection.normalized * MinSpeed;
rbody.velocity = randomDirection;
transform.parent = null;
hasBeenLaunched = true;
}
}
Code for my paddle
public class PaddleScript : MonoBehaviour
{
private float moveSpeed = 15f;
void Start()
{
}
void Update()
{
if (Input.GetKey(KeyCode.RightArrow) && transform.position.x<9.5)
transform.Translate(moveSpeed *Input.GetAxis("Horizontal")*Time.deltaTime, 0f, 0f);
if (Input.GetKey(KeyCode.LeftArrow) && transform.position.x>-7.5)
transform.Translate(moveSpeed *Input.GetAxis("Horizontal")*Time.deltaTime, 0f, 0f);
}
}
The simplest thing you can do to check wether the ball goes off screen is to place a trigger immediately off the perimeter of the camera, and add an OnTriggerEnter2D method to your ball.
/* Inside the ball script */
private void OnTriggerEnter() { // Use the 2D version if you're using 2D colliders
/* Respawning stuff */
}
Since you may want a bunch of different things to happen when that method triggers, you may want to use a Unity Event, which is not the king of performance but it probabily doesn't matter for a game like breakout.
using UnityEngine.Events;
public class BallScript : MonoBehaviour
{
public UnityEvent onBallOut;
/* ... */
private void OnTriggerEnter() {
onBallOut.Invoke();
}
}
You then probabily want a Respawn() method (not Reset() because that's a default MonoBehaviour call) which places the ball back to its original position, which you can store in a field as soon as the scene loads:
private Vector3 defaultPosition;
private void Start() {
defaultPosition = transform.position;
}
PS: If you aren't using the Start() method in your paddle script then remove it, cause it will be called by Unity even if empty.

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 move the camera up the Y axis only when the player reaches the top 1/2 of the screen in Unity C#

This is for a 2D platform game.
I don't want the camera to move up the Y axis when the player jumps. I only want it to move when the player to the upper part of the screen so it can scroll up to vertical platforms and ladders.
Does anybody know what to enter in the code and the Unity editor so that can be done?
Here's the code I have so far in the camera script.
public class CameraControl : MonoBehaviour {
public GameObject target;
public float followAhead;
public float smoothing;
private Vector3 targetPosition;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
targetPosition = new Vector3 (target.transform.position.x, transform.position.y, transform.position.z);
if (target.transform.localScale.x > 0f) {
targetPosition = new Vector3 (targetPosition.x + followAhead, targetPosition.y, targetPosition.z);
} else {
targetPosition = new Vector3 (targetPosition.x - followAhead, targetPosition.y, targetPosition.z);
}
transform.position = Vector3.Lerp (transform.position, targetPosition, smoothing * Time.deltaTime);
}
}
I guess you have a bool tied to the jump which triggers the jumping animation.
So, in the Update() of the camera you can do something like this:
void Update() {
// Update camera X position
if (isPlayerJumping) return;
// Update camera Y position
}
This way, you update the Y position of the camera only if the player isn't jumping, while still updating the X position in all cases (even while jumping).

How Do I Shoot a Projectile into the Direction the Player is Facing?

I am creating a 2D side-scroller video game in Unity using c#. I have created the script that makes the player face the direction that the arrow key that was pressed was pointing to (when the right arrow is pressed, the player faces right. When the left arrow is pressed, the player faces left).
However, I cannot figure out how to make the harpoon that the player shoots point in the direction the player is facing. I have found many questions on Stack Overflow asking questions like this, but none of their answers worked for me.
Can anyone please tell me how to make the harpoon the player shoots face the direction the player is facing? Thanks in advance!
Here is my code that I use-
PLAYER SCRIPT
using UnityEngine;
using System.Collections;
public class playerMove : MonoBehaviour {
// All Variables
public float speed = 10;
private Rigidbody2D rigidBody2D;
private GameObject harpoon_00001;
private bool facingRight = true;
void Awake () {
rigidBody2D = GetComponent<Rigidbody2D>();
harpoon_00001 = GameObject.Find("harpoon_00001");
}
void Update () {
if (Input.GetKeyDown(KeyCode.LeftArrow) && !facingRight) {
Flip();
}
if (Input.GetKeyDown(KeyCode.RightArrow) && facingRight) {
Flip();
}
}
void Flip () {
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
void FixedUpdate () {
float xMove = Input.GetAxis("Horizontal");
float yMove = Input.GetAxis("Vertical");
float xSpeed = xMove * speed;
float ySpeed = yMove * speed;
Vector2 newVelocity = new Vector2(xSpeed, ySpeed);
rigidBody2D.velocity = newVelocity;
if (Input.GetKeyDown("space")) {
GetComponent<AudioSource>().Play();
Instantiate(harpoon_00001,transform.position,transform.rotation);
}
}
}
HARPOON SCRIPT
using UnityEngine;
using System.Collections;
public class harpoonScript : MonoBehaviour {
// Public variable
public int speed = 6;
private Rigidbody2D r2d;
// Function called once when the bullet is created
void Start () {
// Get the rigidbody component
r2d = GetComponent<Rigidbody2D>();
// Make the bullet move upward
float ySpeed = 0;
float xSpeed = -8;
Vector2 newVelocity = new Vector2(xSpeed, ySpeed);
r2d.velocity = newVelocity;
}
void Update () {
if (Input.GetKeyDown(KeyCode.LeftArrow)) {
float xSpeed = -8;
}
if (Input.GetKeyDown(KeyCode.RightArrow)) {
float xSpeed = 8;
}
}
void OnTriggerEnter2D(Collider2D other) //hero hits side of enemy
{
Destroy(other.gameObject.GetComponent<Collider2D>()); //Remove collider to avoid audio replaying
other.gameObject.GetComponent<Renderer>().enabled = false; //Make object invisible
Destroy(other.gameObject, 0.626f); //Destroy object when audio is done playing, destroying it before will cause the audio to stop
}
}
You already defining a variable facingRight to know the direction of the the player. You can use that knowledge to control the harpoon.
For example:
// this line creates a new object, which has harpoonScript attached to it.
// In unity editor, you drag and drop this prefab(harpoon_00001) into right place.
// transform.position is used for the starting point of the fire. You can also add +-some_vector3 for better placement
// Quaternion.identity means no rotation.
harpoonScript harpoon = Instantiate(harpoon_00001,transform.position, Quaternion.identity) as harpoonScript;
// Assuming harpoon prefab already facing to right
if (!facingRight) {
// Maybe, not required
harpoon.transform.eulerAngles = new Vector3(0f, 0f, 180f); // Face backward
Vector3 theScale = harpoon.transform.localScale;
theScale.y *= -1;
harpoon.transform.localScale = theScale; // Flip on y axis
}

Categories