Home > Software engineering >  unity3d Move object to touch point
unity3d Move object to touch point

Time:11-23

I am a beginner programmer. I will not find information on solving my problem. I have a 3d game. Task: When you touch the screen, a bullet is created and flies towards the touch. In my code, the bullet is flying up https://imgur.com/fsBaDSe

if (Input.touchCount > 0)
{
    if (Input.GetTouch(0).phase == TouchPhase.Began)
    {
        Vector2 touchPos = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
        Vector2 dir = touchPos - (new Vector2(transform.position.x, transform.position.z));
        dir.Normalize();
        GameObject bullet = Instantiate(projectile, transform.position, Quaternion.identity) as GameObject;
        bullet.GetComponent<Rigidbody2D>().velocity = dir * bulletSpeed;
    }
}

CodePudding user response:

I would use a raycast for this to find where the bullet is "meant" to travel towards. Explanation in comments:

// define what things the ray ignores
// try different configuration in the inspector to see what works for your game
[SerializeField] LayerMask raycastMask;

// define a default distance for ray use if nothing collides
[Serializefield] float defaultRayDist = 20f;

// Where the bullet is meant to be fired from
[SerializeField] Transform bulletOrigin;

//...

    if (Input.GetTouch(0).phase == TouchPhase.Began)
    {
        // Turn touch into ray
        Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);

        Vector3 dest;
        // Determine if raycast hit occurs
        if (Physics.Raycast(ray, out RaycastHit hitInfo, layerMask: raycastMask))
        {
            // If hit occurs use its position
            dest = hitInfo.point;
        } 
        else 
        {
            // If no hit occurs find point along ray to use as bullet destination
            dest = Ray.GetPoint(defaultRayDist);
        }

        // Optionally, put dest at same height as bulletOrigin
        // dest.y = bulletOrigin.position.y;

        // Find direction from start to destination 
        Vector3 dir = (dest - bulletOrigin.position).normalized;

        // Create bullet and set its rotation and velocity
        GameObject bullet = Instantiate(projectile, bulletOrigin.position,
                Quaternion.LookRotation(dir)) as GameObject;

        bullet.GetComponent<Rigidbody2D>().velocity = dir * bulletSpeed;
    }

CodePudding user response:

First : add colliders to your enemies or what ever you want to shoot at.

Then make a new Game Object and rename it to bullet.

Then make a new C# script called Bulletand add it to your bullet game object. Then turn bullet game object to a prefab. Then put this code in bullet class :

public float speed;
public Rigidbody rb;
Vector3 target;

public void Initialize(Vector3 _target)
{
    target = _target;
    transform.forward = target - transform.position;
}

public void Update()
{
    rb.AddForce(transform.forward * Time.DeltaTime);
}

then make a new C# script called PlayerShoot. Add it to your PLAYER game object and paste this code to it:

public LayerMask shootMask;
public float shootRange;
public Transform player;
public GameObject bulletPrefab;
public Transform shootPos;

public void Update()
{
    foreach(Touch t in Input.touches)
    {
        if(t.phase == TouchPhase.began)
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if(Physics.RayCast(ray, out RaycastHit hit, shootRange, shootMask)
            {
                player.transform.LookAt(new Vector3(hit.point.x, player.position.y, hit.point.z);
            
                Bullet b = Instantiate(bulletPrefab, shootPos.transform.position, shootPos.rotation).GetComponent<Bullet>();

                b.Initialize(hit.point);
            }
        }
    }
}

shootPos is where bullet gonna shoot from and make sure that shootPos forward is in direction that you want to be shooted.

shootRange is how farAway player can shoot. NOTE: if it isnt working bring shootRange upper.

shootMask is what you ganna shoot at. NOTE: if it isnt working add another mask to your players colliders and then uncheck that mask from shootMasks list in PlayerShoot scripts inspector.

CodePudding user response:

Just easy.

public Transform target;
public float depth = 4f;
public void Update()
{
    Vector3 touchPoint = Camera.main.ScreenPointToWorld(new Vector3(Input.mousePosition.x, Input.mousePosition.y, depth);

    target.position = touchPoint;
}

CodePudding user response:

A complete Example :

void Update()
{
    Vector3 touchPoint = Camera.main.ScreenPointToWorld(new 
    Vector3(Input.mousePosition.x, Input.mousePosition.y, depth);

    float speed = .3f; 
    bullet.transform.position = Vector3.Lerp(bullet.transform.position, 
        touchPoint, 
        speed * Time.deltaTime);

    bullet.transform.forward = touchPoint - bullet.transform.position;
}
  • Related