How to Click movement in unity and stop if there is Collider? - c#

so I have an issue about movement click on unity it's about when I click of course the player will be moving to the position I clicked but, I don't want if I clicked on the wall and another button the player will be on the last mouse I clicked, I already add some collider but the player just bypass the collider so collider doesn't have any effect
the explanation
and this the script
[Header("Tweak")]
[SerializeField] Transform target;
Vector2 targetPos;
public float speed = 5f;
// Start is called before the first frame update
void Start()
{
targetPos = transform.position;
}
// Update is called once per frame
void Update()
{
Move();
}
public void Move()
{
if (Input.GetMouseButtonDown(0))
{
targetPos = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
if ((targetPos.x >= transform.position.x))
{
transform.localScale = new Vector2(.5f, .5f);
}
else
{
transform.localScale = new Vector2(-.5f, .5f);
}
target.position = targetPos;
}
if ((Vector2)transform.position != targetPos)
{
transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
}
}

You can do this using Raycast
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
if (hitInfo.collider.gameObject.tag == "Wall")
{
Debug.Log("tag");
//You can do what ever you want here.
}
}
}

Related

Vector3.MoveTowards() isn't working, cant fix it?

I'm really new to coding and English isn't my main language, so forgive any dumb errors and my English.
I'm working on a movement system that moves the player to click point, everything on the script seems to work, but in the game tab the player doesn't move at all. I already read a lot of information about Vector3.MoveTowards(), but nothing worked for me.
Vector3 currentpos;
Vector3 targetpos;
bool ismoving = false;
public float speed = 10f;
void Update()
{
currentpos = transform.position;
move();
if (Input.GetMouseButtonDown(0))
{
click();
}
}
void click() //get the position of the click using a raycast//
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit))
{
targetpos = hit.point;
targetpos.y = 0f; //only whants to move the player in the x and z axis//
ismoving = true;
move();
}
}
void move()
{
if (ismoving==true)
{
if (Vector3.Distance(currentpos,targetpos)>0.1f) //if distance between current position and target position is greater than 0.1f player should move//
{
currentpos = Vector3.MoveTowards(currentpos, targetpos, speed * Time.deltaTime);
Debug.Log("Current Position is:" + currentpos + " and target position is" + targetpos);
}
if(Vector3.Distance(currentpos,targetpos)<0.1f)
{
ismoving = false;
}
}
}
In the console the current position and the target position are right but the player doesn't move.
Well, you are chaning the value of currentpos but never asign it back to transform.position e.g. here
currentpos = Vector3.MoveTowards(currentpos, targetpos, speed * Time.deltaTime);
transform.position = currentpos;

Object Follow Mouse Dragging Unity 3D

I have an object moving forward constantly, I want to make it move on the X axis by mouse dragging any part of the screen (swiping), so I tried this code but when first clicking on the screen the object move to the mouse X position (without dragging)! do you have any suggestions on how to make it move only when dragging?
The Script:
private bool dragging = false;
private float distance;
public Rigidbody Ball;
public float Speed = 100;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
Ball.velocity = transform.forward * Speed * Time.deltaTime;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
distance = Vector3.Distance(transform.position, Camera.main.transform.position);
dragging = true;
}
if(Input.GetMouseButtonUp(0))
{
dragging = false;
}
if (dragging)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 rayPoint = ray.GetPoint(distance);
transform.position = new Vector3(rayPoint.x, transform.position.y, transform.position.z);
}
}
For the continues movement you can use GetMouseButton which is true while the button stays pressed (in contrary to GetMouseButtonDown which is true only the first frame the button is pressed)
You said the script is attached to the same as the RigiBody component. In such a case you should never place an object using
transform.position = ...
but instead use RigidBody.MovePosition like
Ball.MovePosition(new Vector3( ... ));
Finally store the initial position on mouse down and than use it as a reference point:
Vector3 initialPosition;
void Update()
{
// called the first time mouse button is pressed
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
initialPosition = transform.position;
Vector3 rayPoint = ray.GetPoint(0);
// Not sure but this might get you a slightly better value for distance
distance = Vector3.Distance(transform.position, rayPoint );
}
// called while button stays pressed
if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 rayPoint = ray.GetPoint(distance);
Ball.MovePosition(initialPosition + new Vector3(rayPoint.x, 0, 0));
}
}
Also note that I'm not sure that
// Update is called once per frame
void FixedUpdate () {
Ball.velocity = transform.forward * Speed * Time.deltaTime;
}
is what you want to do. The usage of Time.deltaTime makes not much sense here in my eyes. You either want to set the velocity to a certain speed like
Ball.velocity = transform.forward * Speed;
or you want to change a position using Time.deltaTime to have a smooth movement like
Ball.MovePosition(transform.position + transform.forward * Speed * Time.deltaTime);

Auto shoot script for VR? (changing Script)

I am integrating my game to VR and now i wanted to change my controlling. In the script given bellow when the player press the mouse button the gun fires the bullet but now in VR i don't want my game to be controlled by any controller. what i want is when player moves his head and the focus point comes to the Enemy it starts shooting without pressing any button(I mean auto shoot). what should i do??
grausing System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunScript : MonoBehaviour {
public float damage = 10f;
public float range = 100f;
public float fireRate = 15f;
public float impactForce = 30f;
public Camera fpsCam;
public GameObject impactEffect;
private float nextTimeToFire = 0f;
// Update is called once per frame
void Update () {
if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire)
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
}
}
void Shoot()
{
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
}
if(hit.rigidbody != null)
{
hit.rigidbody.AddForce(-hit.normal * impactForce);
}
GameObject ImpactEffectGO = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(ImpactEffectGO, 2f);
}
}
}
Since you already have an existing shooting mechanic, simply changing up the Update() should do what you want
void Update () {
if (Time.time >= nextTimeToFire)
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
}
}

Moving player towards clicked point in Unity 2D

I am making a 2D point-and-click game where i want the player to move towards clicked objects. This is my code for moving the player towards a door:
using UnityEngine;
using System.Collections;
public class MoveOnClick : MonoBehaviour {
public GameObject door;
public GameObject player;
public float speed;
public Vector3 target;
void Update () {
if (Input.GetMouseButtonDown (0)) {
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector3.zero);
if (hit.collider != null) {
player.transform.position = Vector3.MoveTowards(player.transform.position, target, speed * Time.deltaTime);
}
}
}
}
The problem is that the player only moves one pixel per click. I want the player to move all the way to the door if the door is clicked.
That should work:
void Update () {
if (Input.GetMouseButtonDown (0)) {
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector3.zero);
target = hit.transform.position;
}
if (hit.collider != null) {
player.transform.position = Vector3.MoveTowards(player.transform.position, target, speed * Time.deltaTime);
}
}

Get player to jump with touch screen control

Hello and thanks for reading this post.
I have 2 objects: A player Object and a JumpButton Object.
The Player object is the player. ofc. The JumpButton Object is an object that I want to make the player jump when you use a touch screen device aka android phone.
This is my Script that is assinged to my JumpButton: using UnityEngine; using System.Collections;
using UnityEngine;
using System.Collections;
public class JumpButtonScript : MonoBehaviour {
public GameObject player;
public GameObject JumpButton;
// Use this for initialization
void Start () {
player = GameObject.Find ("player");
}
// Update is called once per frame
void Update () {
if ((Input.touchCount == 1) && (Input.GetTouch(0).phase == TouchPhase.Began))
{
}
}
}
This is the script that allows me to control the player with arrow keys.
using UnityEngine;
using System.Collections;
public class RobotController : MonoBehaviour {
//This will be our maximum speed as we will always be multiplying by 1
public float maxSpeed = 2f;
public GameObject player;
public GameObject sprite;
//a boolean value to represent whether we are facing left or not
bool facingLeft = true;
//a value to represent our Animator
Animator anim;
//to check ground and to have a jumpforce we can change in the editor
bool grounded = true;
public Transform groundCheck;
public float groundRadius = 1f;
public LayerMask whatIsGround;
public float jumpForce = 300f;
private bool isOnGround = false;
void OnCollisionEnter2D(Collision2D collision) {
isOnGround = true;
}
void OnCollisionExit2D(Collision2D collision) {
anim.SetBool ("Ground", grounded);
anim.SetFloat ("vSpeed", rigidbody2D.velocity.y);
isOnGround = false;
}
// Use this for initialization
void Start () {
player = GameObject.Find("player");
//set anim to our animator
anim = GetComponent <Animator>();
}
void FixedUpdate () {
//set our vSpeed
//set our grounded bool
grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);
//set ground in our Animator to match grounded
anim.SetBool ("Ground", grounded);
float move = Input.GetAxis ("Horizontal");//Gives us of one if we are moving via the arrow keys
//move our Players rigidbody
rigidbody2D.velocity = new Vector3 (move * maxSpeed, rigidbody2D.velocity.y);
//set our speed
anim.SetFloat ("Speed",Mathf.Abs (move));
//if we are moving left but not facing left flip, and vice versa
if (move > 0 && !facingLeft) {
Flip ();
} else if (move < 0 && facingLeft) {
Flip ();
}
}
void Update(){
if ((isOnGround == true && Input.GetKeyDown (KeyCode.UpArrow)) || (isOnGround == true && Input.GetKeyDown (KeyCode.Space))) {
anim.SetBool("Ground",false);
rigidbody2D.AddForce (new Vector2 (0, jumpForce));
}
if (isOnGround == true && Input.GetKeyDown (KeyCode.DownArrow))
{
gameObject.transform.localScale = new Vector3(transform.localScale.x, 0.2f, 0.2f);
}
if (isOnGround == true && Input.GetKeyUp (KeyCode.DownArrow))
{
gameObject.transform.localScale = new Vector3(transform.localScale.x, 0.3f, 0.3f);
}
}
//flip if needed
void Flip(){
facingLeft = !facingLeft;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
As you can see, then I managed to make the player move on arrow keys, but how can I make it jump when I hit the jump button (touch Screen press), as on an Android Phone?
I really hope you can help me.
If your problem is how to handle input, try this code we will make ray from camera to mousepos in screen and check tag to see what we hitted
public class handleInput: MonoBehaviour {
void Update () {
if (Input.GetMouseButtonDown (0)) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit)) {
if (hit.collider.tag=="jumpbutton"){
jump();
}
}
}
}
}
and for the jumping part you can do this , adding a force to player to send him up and gravity should pull him down
if (grounded == true)
{
rigidbody.AddForce(Vector3.up* jumpSpeed);
grounded = false;
}

Categories

Resources