Rotating an object using raycasts [Edit: now rotating using each side of the screen]

I’m making a top down game on android, with a cannon in the middle of my scene, it starts of facing up. What I would like to do is rotate the cannon based on where the player presses on screen. So if I press on the bottom part of the screen the cannon will rotate around and point down while staying in its fixed position.

I think I can use raycasts for this, in theory it would be:

  • User presses on part of the screen
  • A ray hits the plane under the cannon
  • The cannon detects where the ray hit and rotates to that position

That’s it in theory, I just don’t know how to put it into practise, if anyone could help, i’d appreciate it.

Try this

void update()
	{

	if (Input.touches.Length > 0) 
	{
		if (Input.GetTouch(0).phase == TouchPhase.Began) 
		{
			Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
			RaycastHit hit;
			Vector3 hitPos;
			if (Physics.Raycast(ray, out hit)) 
				{
					hitPos = hit.point - transform.position;
				}
			
			Quaternion look = Quaternion.LookRotation(hitPos);
			transform.rotation = Quaternion.Slerp(transform.rotation, look, Time.deltaTime * 5);
			
		}
	}
	}

attach this to your cannon

So i’ve decided to scrap movement based on raycasting and will now turn the turret to the left or right based on what side of the screen the user presses. Here is the working code:

using UnityEngine;
using System.Collections;

public class turretMovement : MonoBehaviour 
{

	void Update()
	{
		
		if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Stationary)
		{
			Vector2 touchPosition = Input.GetTouch (0).position;
			float halfScreen = Screen.width / 2.0f;
			
			//Check if it's left or right
			if(touchPosition.x < halfScreen)
			{
				transform.Rotate (Vector3.up * 100 * Time.deltaTime);
			}
			
			else if (touchPosition.x > halfScreen)
			{
				transform.Rotate (Vector3.down * 100 * Time.deltaTime);
			}
		}
		
	}
}