Kivy Angle Examples - touch

Angle rotation only works on the first example
I want to understand. Why one example with the angle animation call works and the other fails.
From what I can gather, this has to do with the Builder.load_string.
Working Example
#working example
from kivy.lang import Builder
from kivy.base import runTouchApp
from kivy.uix.image import Image
from kivy.graphics import Rotate
from kivy.properties import NumericProperty
from math import atan2, degrees
from kivy.animation import Animation
Builder.load_string('''
<PlayerImage>:
canvas.before:
PushMatrix
Rotate:
angle: self.angle
axis: (0, 0, 1)
origin: self.center
canvas.after:
PopMatrix
''')
class PlayerImage(Image):
angle = NumericProperty(0)
def on_touch_down(self, touch):
Animation.cancel_all(self)
angle = degrees(atan2(touch.y - self.center_y,
touch.x - self.center_x))
Animation(center=touch.pos, angle=angle).start(self)
root = Builder.load_string('''
Widget:
PlayerImage:
source: 'images/example.png'
allow_stretch: True
keep_ratio: False
''')
runTouchApp(root)
Non Working Example
from kivy.lang import Builder
from kivy.base import runTouchApp
from kivy.uix.image import Image
from kivy.graphics import Rotate
from kivy.properties import NumericProperty
from math import atan2, degrees
from kivy.animation import Animation
class PlayerImage(Image):
angle = NumericProperty(0)
def on_touch_down(self, touch):
Animation.cancel_all(self)
angle = degrees(atan2(touch.y - self.center_y,
touch.x - self.center_x))
Animation(center=touch.pos, angle=angle).start(self)
root = Builder.load_string('''
Widget:
PlayerImage:
source: 'images/example.png'
allow_stretch: True
keep_ratio: False
canvas.before:
PushMatrix
Rotate:
angle: self.angle
axis: (0, 0, 1)
origin: self.center
canvas.after:
PopMatrix
''')
runTouchApp(root)

The second KVlang block is incorrect, there is excess indentation on the Rotate (and, for stylistic purposes, a missing ":" after the PushMatrix).

Related

Cannot import pygame.camera

I was trying this code to open a webcam with pygame
import pygame.camera
import pygame.image
import sys
pygame.camera.init()
cameras = pygame.camera.list_cameras()
print ("Using camera %s ..." % cameras[0])
webcam = pygame.camera.Camera(cameras[0])
webcam.start()
# grab first frame
img = webcam.get_image()
WIDTH = img.get_width()
HEIGHT = img.get_height()
screen = pygame.display.set_mode( ( WIDTH, HEIGHT ) )
pygame.display.set_caption("pyGame Camera View")
while True :
for e in pygame.event.get() :
if e.type == pygame.QUIT :
sys.exit()
# draw frame
screen.blit(img, (0,0))
pygame.display.flip()
# grab next frame
img = webcam.get_image()
but I got this import error:
...Python\Python39\lib\site-packages\pygame_camera_vidcapture.py", line 32, in init
from VideoCapture import vidcap as vc
ModuleNotFoundError: No module named 'VideoCapture'
Enter
pip install pygame.camera
into your terminal or command prompt depending on what you are using.

Unable to draw multiple instace of same Image with GraphicsContext

Hi guys this is my first question, so feel free to give constructive criticism.
I am making a space shooter game with ScalaFX and I'm facing a problem where when I am drawing the bullet laser in my AnimationTimer loop, whenever the player shoots another bullet, the program only renders the newest bullet and the old bullet just disappears.
For the sake of brevity, I'm going to post the main AnimationTimer loop related to the bullet input and rendering only:
//List of stuffs (Bullets, enemies etc)
var laserListB : ListBuffer[Laser] = ListBuffer()
val timer = AnimationTimer( currentNanoTime => {
//Calculating time since last frame for frame independant rendering
var elapsedTime : Double = (currentNanoTime - lastNanoTime) / 1000000000.0;
lastNanoTime = currentNanoTime;
//Input check
//SKIPPED PLAYER MOVEMENT CODE
if(shootPress){
var now = System.nanoTime()
//Checking for atkSpeed cooldwon
if((lastShootNano <= 0L) || ((now - lastShootNano) >= player.atkSpeed)){
laserListB += player.shoot()
}
lastShootNano = now
}
//Updating position
for(laser <- laserListB){
laser.sprite.velocityX = 0
laser.sprite.velocityY = -400
laser.sprite.update(elapsedTime)
}
//Rendering
//Bullets
for(laser <- laserListB){
laser.sprite.render(gc)
}
})
And the following is my Sprite class:
import scalafx.scene.image.Image
import scalafx.scene.canvas.GraphicsContext
import scalafx.geometry.Rectangle2D
class Sprite(
private var _image : Image,
private var _positionX : Double,
private var _positionY : Double,
private var _velocityX : Double,
private var _velocityY : Double,
private var _width : Double,
private var _height : Double){
//Functions
def render(gc : GraphicsContext){
gc.drawImage(_image, _positionX, _positionY);
}
}
And if you need, here's my player's shoot function:
def shoot() = {
//Setting up laser sprite
val laser = new Laser(_atkSprite, damage, true)
laser.sprite.velocityX = 0
laser.sprite.velocityY = -400
laser.sprite.positionX = _sprite.positionX + (_sprite.width / 2) //Center laser horizontally on player sprite
laser.sprite.positionY = _sprite.positionY - 10 //Slight offset to be a bit higher than the player sprite
laser
}
Thank you for reading this far :D
Edit 1:
Here's a video demonstrating the problem: https://youtu.be/DliNyBoa1DI
Ok I solved it, it wasn't a problem with GraphicsContext but rather due to the fact, Laser is instantiated with the same Sprite in player.shoot(), therefore all Lasers will have the same X and Y, and be overlapped, thus appearing as if it "disappeared".
The new code instantiates a new Sprite everytime Laser is instantiated as follows:
def shoot() = {
//Laser sprites
val atkImg = new Image(getClass.getResourceAsStream("/Images/small_laser_blue.png"))
val atkSprite = new Sprite(atkImg, 0, 0, 0, 0, atkImg.getWidth(), atkImg.getHeight())
val laser_ = new Laser(atkSprite, _damage, true)
laser_.sprite.velocityX = 0
laser_.sprite.velocityY = -400
laser_.sprite.positionX = _sprite.positionX + (_sprite.width / 2) //Center laser horizontally on player sprite
laser_.sprite.positionY = _sprite.positionY - 10 //Slight offset to be a bit higher than the player sprite
}

How to rotate a bone to a specific position programmatically?

Suppose I have a human skeleton standing upright in the following position:
Say I want to modify the 3d model, so that it is raising one hand (everything else the same):
I couldn't find a picture of a skeleton standing upright, so I posted the above picture, but you can imagine if the skeleton was standing exactly how it was in the first picture, with the only difference being it had rotated its right should to raise its right hand perfectly upright, what would it look like?
To further illustrate the idea, if you visit this link:
Motion capture visualisation with Blender
The code he uses to update the 3d model in blender is actually quite small and simple:
import bge
import math
from math import *
import mathutils
import time
import sys
#sys.path.append("/usr/lib/python3/dist-packages")
import serial
import glob
port=''.join(glob.glob("/dev/ttyACM*"))
#port=''.join(glob.glob("/dev/ttyUSB*"))
#port=''.join(glob.glob("/dev/rfcomm"))
ser = serial.Serial(port,115200)
print("connected to: " + ser.portstr)
#Connect the suit first and after a ~second launch the script
# Get the whole bge scene
scene = bge.logic.getCurrentScene()
# Helper vars for convenience
source = scene.objects
# Get the whole Armature
main_arm = source.get('Armature')
ob = bge.logic.getCurrentController().owner
def updateAngles():
ser.write("a".encode('UTF-8'))
s=ser.readline()[:-3].decode('UTF-8') #delete ";\r\n"
angles=[x.split(',') for x in s.split(';')]
for i in range(len(angles)):
angles[i] = [float(x) for x in angles[i]]
trunk = mathutils.Quaternion((angles[4][0],angles[4][1],angles[4][2],angles[4][3]))
correction = mathutils.Quaternion((1.0, 0.0, 0.0), math.radians(90.0))
trunk_out = correction*trunk
upperLegR = mathutils.Quaternion((angles[5][0],angles[5][1],angles[5][2],angles[5][3]))
correction = mathutils.Quaternion((1.0, 0.0, 0.0), math.radians(90.0))
upperLegR_out = correction*upperLegR
lowerLegR = mathutils.Quaternion((angles[6][0],angles[6][1],angles[6][2],angles[6][3]))
correction = mathutils.Quaternion((1.0, 0.0, 0.0), math.radians(90.0))
#correction = mathutils.Quaternion((1.0, 0.0, 0.0), math.radians(90.0))
lowerLegR_out = correction*lowerLegR
upperLegL = mathutils.Quaternion((angles[7][0],angles[7][1],angles[7][2],angles[7][3]))
correction = mathutils.Quaternion((1.0, 0.0, 0.0), math.radians(90.0))
upperLegL_out = correction*upperLegL
lowerLegL = mathutils.Quaternion((angles[8][0],angles[8][1],angles[8][2],angles[8][3]))
correction = mathutils.Quaternion((1.0, 0.0, 0.0), math.radians(90.0))
lowerLegL_out = correction*lowerLegL
ob.channels['armR'].rotation_quaternion = mathutils.Vector([angles[0][0],angles[0][1],angles[0][2],angles[0][3]])
ob.channels['forearmR'].rotation_quaternion = mathutils.Vector([angles[1][0],angles[1][1],angles[1][2],angles[1][3]])
ob.channels['armL'].rotation_quaternion = mathutils.Vector([angles[2][0],angles[2][1],angles[2][2],angles[2][3]])
ob.channels['forearmL'].rotation_quaternion = mathutils.Vector([angles[3][0],angles[3][1],angles[3][2],angles[3][3]])
ob.channels['trunk'].rotation_quaternion = trunk_out
ob.channels['upperLegR'].rotation_quaternion = upperLegR_out
ob.channels['lowerLegR'].rotation_quaternion = lowerLegR_out
ob.channels['upperLegL'].rotation_quaternion = upperLegL_out
ob.channels['lowerLegL'].rotation_quaternion = lowerLegL_out
ob.update()
time.sleep(0.001)
Is there an equivalent way in Unity3d, to access a particular bone in a 3d model, and set its rotation ?
See this video:
https://www.youtube.com/watch?time_continue=26&v=JddtxynTgLk
As you can see, he is reading the values from the sensor, and updating the 3d model in blender in real time. I've done the sensor part, but am just getting started with Unity, and was wondering how to access individual bones and set them similar to the above code.
EDIT: In Godot engine, they seem to be able to do it very simply, see the link below:
https://docs.godotengine.org/en/3.0/tutorials/3d/working_with_3d_skeletons.html
extends Spatial
var skel
var id
func _ready():
skel = get_node("skel")
id = skel.find_bone("upperarm")
print("bone id:", id)
var parent = skel.get_bone_parent(id)
print("bone parent id:", id)
var t = skel.get_bone_pose(id)
print("bone transform: ", t)
set_process(true)
func _process(delta):
var t = skel.get_bone_pose(id)
t = t.rotated(Vector3(0.0, 1.0, 0.0), 0.1 * delta)
skel.set_bone_pose(id, t)
As you can see, in the Godot example also, once they get the bones id, they simply need to set the angle.

Drawing a Rectangle with color and thickness in OnGUI

I would like to draw a frame / rectangle in OnGUI in order to display a certain area for debugging purposes.
This rectangle should be displayed with a certain "thickness" / line width and color.
So far, I have only found GUI.Label and GUI.Box, which both seems inadequate for this.
Thank you!
If it is only for debugging I would recommend to use Gizmos.DrawWireCube
Note: Only drawn in the SceneView not in the GameView so really only for debugging
private void OnDrawGizmosSelected()
{
// Draw a yellow cube at the transform position
var color = Gizmos.color;
Gizmos.color = Color.yellow;
Gizmos.DrawWireCube(transform.position, new Vector3(1, 1, 1));
Gizmos.color = color;
}
for showing it only if object is selected or OnDrawGizmos for showing it allways
Note that this is done in WorldSpace so if you rather want the size vector etc rotate together with the object you can wrap in between
var matrix = Gizmos.matrix;
Gizmos.matrix = transform.localToWorldMatrix;
//...
Gizmos.matrix = matrix;
Unfortunately there is no option to change the line thikness...
... but you could overcome this by simply drawing e.g. 4 normal cubes using Gizmos.DrawCube to form a rectangle. Something maybe like
private void OnDrawGizmos()
{
DrawDebugRect(new Vector2(0.5f, 0.3f), 0.05f);
}
private void DrawRect(Vector2 size, float thikness)
{
var matrix = Gizmos.matrix;
Gizmos.matrix = transform.localToWorldMatrix;
//top cube
Gizmos.DrawCube(Vector3.up * size.y / 2, new Vector3(size.x, thikness, 0.01f);
//bottom cube
Gizmos.DrawCube(Vector3.down * size.y / 2, new Vector3(size.x, thikness, 0.01f);
//left cube
Gizmos.DrawCube(Vector3.left * size.x / 2, new Vector3(thikness, size.y, 0.01f);
//right cube
Gizmos.DrawCube(Vector3.right * size.x / 2, new Vector3(thikness, size.y, 0.01f);
Gizmos.matrix = matrix;
}
I'm only on smartphone so it might not be copy-past-able but I think you'll get the idea ;)

AS3 Starling: How to remove black bars on top and bottom of iPhone 6+/...?

I'm just trying out Starling Framework for Actionscript 3 and I have a "big" problem with removing these ugly black bars on top and bottom of my iPhone 6+.
I tried to fix it with: http://wiki.starling-framework.org/manual/multi-resolution_development and http://forum.starling-framework.org/topic/game-not-full-screen-when-testing-in-ios
But it still wont work :(
Any Ideas?
package {
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.geom.Rectangle;
import starling.core.Starling;
import starling.events.ResizeEvent;
import starling.utils.HAlign;
import starling.utils.VAlign;
public class FooBar extends Sprite {
private
var _starling: Starling;
public
function CHouseApp() {
super();
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
Starling.handleLostContext = true;
var screenWidth: int = stage.fullScreenWidth;
var screenHeight: int = stage.fullScreenHeight;
var viewPort: Rectangle = new Rectangle(0, 0, screenWidth, screenHeight)
_starling = new Starling(MainApplication, stage, viewPort);
_starling.stage.stageWidth = 320;
_starling.stage.stageHeight = 480;
_starling.showStats = true;
_starling.showStatsAt(HAlign.LEFT, VAlign.BOTTOM);
_starling.start();
}
}
}
Screnshot:
(Black bars are marked with red arrow)
You need to include a launch image of name Default-568h#2x.png, of size 640x1136, Default-667h#2x of size 750x1334, Default-736h#3x of size 1242x2208 or iOS will launch the app with a resolution of 640x960, giving you the black bars. You can read the official documentation here
I got it!
I just had to add the following png's to the src folder! so simple :O
Default-375w-667h#2x.png
Default-414w-736h#3x.png
Default-568h#2x.png
Default.png
Default#2x.png
List item