Unity: SetPixal on a texture at mouse position (2D) - unity3d

I am trying to draw on a texture but I don't know the math to convert my mouse position to the texture position.
Currently, the code will draw on the texture but the coordinates are very off.
If someone can help me with this I would appreciate it.
var mousePosition = Input.mousePosition;
var drawPosition = new Vector2(mousePosition.x, mousePosition.y);
for (int x = 0; x < brushSize; x++)
{
for (int y = 0; y < brushSize; y++)
{
m_Texture.SetPixel(x + (int)drawPosition.x, y + (int)drawPosition.y, Color.clear);
}
}
m_Texture.Apply();

Try this:
Vector2 pos;
void Update(){
RectTransformUtility.ScreenPointToLocalPointInRectangle(
parentCanvas.transform as RectTransform, Input.mousePosition,
parentCanvas.worldCamera,
out pos);
}
Assign the parentCanvas and use the pos.x and pos.y inside your for loops

Related

Unity loop Application.EnterPlayMode

When I hit Play Unity makes me wait infinite time before start the scene. The message in Hold On window is "Application.EnterPlayMode Waiting for Unity's code to finish executing". There is only one scene in URP with global volume, directional light and a plane with this script:
using UnityEngine;
public class PerlinNoise : MonoBehaviour
{
[Header("Resolution")]
[Space]
public int width = 256;
public int heigth = 256;
[Space]
[Header("Adjustments")]
[Space]
public float scale = 20;
public float xOffset = 10;
public float yOffset = 10;
void Update()
{
Renderer renderer = GetComponent<Renderer>();
renderer.material.mainTexture = GenerateTexture();
}
Texture2D GenerateTexture()
{
Texture2D texture = new Texture2D(width, heigth);
for (int x = 0; x < width; x++)
{
for (int y = 0; x < heigth; y++)
{
Color color = GenerateColor(x, y);
texture.SetPixel(width, heigth, color);
}
}
texture.Apply();
return texture;
}
Color GenerateColor(int x, int y)
{
float xCoord = (float)x / width * scale + xOffset;
float yCoord = (float)y / width * scale + yOffset;
float perlinNoise = Mathf.PerlinNoise(xCoord, yCoord);
return new Color(perlinNoise, perlinNoise, perlinNoise);
}
}
I tried to kill unity editor task in task manager and restart unity but the same issue repeats. Please help me
You have an infinite loop inside your GenerateTexture method. Specifically, the condition in the nested loop (for y) is accidentally checking for x:
for (int x = 0; x < width; x++)
{
for (int y = 0; x < heigth; y++) // x < height SHOULD BE y < height
{
Color color = GenerateColor(x, y);
texture.SetPixel(width, heigth, color); // this should probably be (x, y, color)
}
}

Two different classes with random values have the same output

I am making the Bouncing Ball using Processing. It works fine when I use the ball object once, but when I use it twice like ball1 & ball2, the balls appear on top of each other making the delusion that it is just one ball bouncing, although I'm setting their primary location and velocity a random number. So, where is the problem? (first argument is for velocity and the second is for x Coordinate)
Main class:
Ball ball1 = new Ball(int(random(0, 2)),int(random(width)));
Ball ball2 = new Ball(int(random(0, 2)),int(random(width)));
void setup() {
// Windows configurations
size(640, 360);
background(50);
}
void draw() {
// Draw the circle
ball1.display();
// Circle movements
ball1.movements();
// Movement limits
ball1.movementLimits();
// Draw the circle
ball2.display();
// Circle movements
ball2.movements();
// Movement limits
ball2.movementLimits();
}
Ball class:
float xCoordinates;
float yCoordinates;
float xVelocity;
float yVelocity;
final float gravity = 0.1;
class Ball {
Ball(int Velocity, int Coordinates) {
xCoordinates = Coordinates;
yCoordinates = height / 6;
if (Velocity == 0)
xVelocity = 2;
else
xVelocity = -2;
if (Velocity == 0)
yVelocity = 2;
else
yVelocity = -2;
}
void movementLimits() {
if (xCoordinates - 10 <= 0 || xCoordinates + 10 >= width)
xVelocity *= -1;
if (yCoordinates + 10 >= height)
yVelocity *= -0.9;
if (yCoordinates - 10 <= 0)
yVelocity *= -1;
}
void movements() {
xCoordinates += xVelocity;
yCoordinates += yVelocity;
yVelocity += gravity;
}
void display() {
background(50);
fill(255);
stroke(255);
circle(xCoordinates, yCoordinates, 20);
}
}
Problem 1:
Both of your objects are shaing the same cooridinates and velocity. They are stored globally so when one object changes it, the change is used by the other object as well. To fix this you should give your Ball class properties to hold the coordinates and velocities.
class Ball{
float x;
float y;
float dx;
float dy
public Ball(float x, float y, float dx, float dy){
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
}
}
Problem 2:
In the display function in Ball, you call background(50);. This will basicly cover the entire screan with the new background; over any previous balls which includes ball1. However, if you remove this line you'll get a kind of cool effect cause by all previous ball drawing sticking around. You should move the background(50); line to the beginning of the draw function. This way, you draw the two balls, draw over them with gray, then redraw the two balls in their new positions.

how to Instantiate prefab with view as a grid in side camera view

i want to create a view like grid with prefabs inside camera view but i'm unable to do so. prefabs are going out of the camera view. can any one help me to resolve this? i want to place prefab as a grid and 9 * 6 grid.
public GameObject tilePrefab;
Vector2 mapSize;
void Start()
{
createGrid();
Debug.Log("Screen Width : " + Screen.width);
Debug.Log("Screen Height : " + Screen.height);
mapSize = new Vector2(Screen.width/9,Screen.height/12);
Debug.Log("mapSize : " + mapSize);
}
void createGrid()
{
for (int x = 0; x < 9; x++)
{
for (int y = 0; y < 6; y++)
{
Vector3 tilePosition = new Vector3(-mapSize.x+0.5f + x,-mapSize.y + 0.5f+y ,0 );
GameObject ballclone = (GameObject)Instantiate(tilePrefab,tilePosition,Quaternion.identity);
ballclone.transform.parent = transform;
}
}
}
You can use ViewportToWorldPoint
for (int x = 0; x < 9; x++)
for (int y = 0; y < 6; y++)
xx.position = camera.ViewportToWorldPoint(new Vector3(1f/9*x, 1f/6*y, distance));
distance is the distance between the camera and the object.

Implement transform.Rotate using rotation matrix

I'm trying to implement transform.Rotate on the y axis in Unity using rotation matrix, is it possible? I wrote this function but it doesn't seems to work, pos is the position of the object to rotate and theta is the angle
public static MyQuaternion Rotate(Vector3 pos, float theta)
{
pos = pos.normalized;
pos -= pos;
float[,] m = new float[3, 3];
m[0, 0] = Mathf.Cos(theta);
m[0, 1] = 0;
m[0, 2] = Mathf.Sin(theta);
m[1, 0] = 0;
m[1, 1] = 1;
m[1, 2] = 0;
m[2, 0] = -Mathf.Sin(theta);
m[2, 1] = 0;
m[2, 2] = Mathf.Cos(theta);
Vector3 newPos = new Vector3();
float temp;
for (int i = 0; i < 3; ++i)
{
temp = 0;
for (int j = 0; j < 3; ++j)
{
temp += m[i, j] * pos[j];
}
newPos[i] = temp;
}
newPos += pos;
return new MyQuaternion(newPos.x, newPos.y, newPos.z, 0);
}
Do you have any idea? Thanks
If you want to get deeply into rotating a vector by hand, you are sort of doing it all right, however I am not sure about the type MyQuaternion you are returning.
If you just want to rotate a vector by an arbitrary angle you can just use Unity's build in Quaternion class. The mutliplication by Vector3 is defined as rotation of that vector so you can just do
Quaternion q=Quaternion.Euler(theta,0,0); // or however you want to map it
Vector3 rotatedVector=q*inputVector;
return rotatedVector;
Rotation in unity is generally done via Quaternion multiplication. To apply it to a gameobject, simply multiply its transform by a rotation you want to perform.
transform.rotation*=Quaternion.Euler(0,0,theta);
Position of an object does not have any play in rotation.

Getting the correct position of an instantiated prefab

When my game starts, I'm instantiating a prefab several times:
for (int y = 0; y < gridY; y++) {
for (int x = 0; x < gridX; x++) {
Vector3 pos = new Vector3 (x, 0, y) * spacing;
Instantiate(prefab, pos, Quaternion.identity);
}
}
This works fine - the objects are displayed correctly in the scene.
The prefab got a script attached, which prints the objects position to the debug output when you right click it. The problem I'm facing is that all these prefabs are returning the same position?
--edit
This is the code I use to print the coordinates:
if (Input.GetMouseButtonDown(1)) {
Debug.Log(transform.position.ToString());
}